You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
122 lines
2.7 KiB
122 lines
2.7 KiB
using UnityEngine; |
|
using System; |
|
using System.Collections.Generic; |
|
using AX.AudioSystem; |
|
|
|
public class MicrophoneTest : MonoBehaviour |
|
{ |
|
public int recordTime = 60; |
|
public int deviceId = 0; |
|
|
|
int deviceCount; |
|
string frequency = "8000"; |
|
string log = ""; |
|
|
|
public AudioSource audioRecorder; |
|
public AudioSource audioPlayer; |
|
|
|
float[] array; |
|
|
|
public volatile bool IsRecording; |
|
|
|
void Start() |
|
{ |
|
audioRecorder = GetComponent<AudioSource>(); |
|
} |
|
|
|
void Log(string log) |
|
{ |
|
this.log += log; |
|
this.log += "\r\n"; |
|
} |
|
|
|
void OnGUI() |
|
{ |
|
deviceCount = Microphone.devices.Length; |
|
|
|
if (deviceCount == 0) |
|
{ |
|
Log("没有发现麦克风!"); |
|
return; |
|
} |
|
|
|
GUILayout.BeginArea(new Rect(400, 0, Screen.width - 400, 600)); |
|
GUILayout.BeginVertical(); |
|
GUILayout.Label("麦克风测试:"); |
|
|
|
if (deviceCount > 0) |
|
{ |
|
GUILayout.BeginHorizontal(); |
|
|
|
GUILayout.BeginVertical(); |
|
|
|
if (GUILayout.Button("开始录音")) |
|
StartRecord(); |
|
|
|
if (GUILayout.Button("停止录音")) |
|
StopRecord(); |
|
|
|
GUILayout.EndVertical(); |
|
|
|
if (GUILayout.Button("播放")) |
|
PlayRecord(); |
|
|
|
frequency = GUILayout.TextField(frequency); |
|
|
|
GUILayout.EndHorizontal(); |
|
} |
|
|
|
GUILayout.Label(log); |
|
GUILayout.EndVertical(); |
|
GUILayout.EndArea(); |
|
} |
|
|
|
void StartRecord() |
|
{ |
|
audioRecorder.Stop(); |
|
audioRecorder.loop = false; |
|
audioRecorder.mute = true; |
|
audioRecorder.clip = Microphone.Start(Microphone.devices[deviceId], false, recordTime, int.Parse(frequency)); |
|
|
|
IsRecording = true; |
|
|
|
Log("开始录音!"); |
|
} |
|
|
|
void StopRecord() |
|
{ |
|
if (!Microphone.IsRecording(Microphone.devices[deviceId])) |
|
return; |
|
|
|
var pos = Microphone.GetPosition(Microphone.devices[deviceId]); |
|
Microphone.End(Microphone.devices[deviceId]); |
|
|
|
IsRecording = false; |
|
|
|
array = new float[pos * audioRecorder.clip.channels]; |
|
|
|
audioRecorder.clip.GetData(array, 0); |
|
|
|
var clip = AudioClip.Create("VoicePlay", pos, audioRecorder.clip.channels, audioRecorder.clip.frequency, false); |
|
|
|
clip.SetData(array, 0); |
|
|
|
audioPlayer.clip = clip; |
|
} |
|
|
|
void PlayRecord() |
|
{ |
|
if (Microphone.IsRecording(Microphone.devices[deviceId])) |
|
return; |
|
|
|
if (audioRecorder.clip == null) |
|
return; |
|
|
|
if (audioPlayer.clip == null) |
|
return; |
|
|
|
audioPlayer.mute = false; |
|
audioPlayer.loop = false; |
|
audioPlayer.Play(); |
|
} |
|
} |