using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AudioTest : MonoBehaviour {
private AudioSource _AudioSource;
public AudioSource myAudioSource
{
get
{
if(myAudioSource ==null )
{
_AudioSource = gameObject.AddComponent<AudioSource>();
}
return _AudioSource;
}
}
private int deviceCount;
string sFrequency = "10000";
string sLog = "";
void Start()
{
string[] ms = Microphone.devices;
deviceCount = ms.Length;
if(deviceCount == 0)
{
print("没有发现耳机!");
}
}
void OnGUI()
{
if (deviceCount > 0)
{
GUILayout.BeginHorizontal();
if (!Microphone.IsRecording(null) && GUILayout.Button("Start", GUILayout.Height(Screen.height / 20), GUILayout.Width(Screen.width / 5)))
{
StartRecord();
}
if (Microphone.IsRecording(null) && GUILayout.Button("Stop", GUILayout.Height(Screen.height / 20), GUILayout.Width(Screen.width / 5)))
{
StopRecord();
}
if (!Microphone.IsRecording(null) && GUILayout.Button("Play", GUILayout.Height(Screen.height / 20), GUILayout.Width(Screen.width / 5)))
{
PlayRecord();
}
if (!Microphone.IsRecording(null) && GUILayout.Button("Print", GUILayout.Height(Screen.height / 20), GUILayout.Width(Screen.width / 5)))
{
PrintRecord();
}
sFrequency = GUILayout.TextField(sFrequency, GUILayout.Width(Screen.width / 5), GUILayout.Height(Screen.height / 20));
GUILayout.EndHorizontal();
}
GUILayout.Label(sLog);
}
private void StartRecord()
{
myAudioSource.Stop();
myAudioSource.loop = false;
myAudioSource.mute = true;
myAudioSource.clip = Microphone.Start(null, false, 1, int.Parse(sFrequency));
while (!(Microphone.GetPosition(null) > 0)) { }
myAudioSource.Play();
print("开始收音!");
}
private void StopRecord()
{
if(!Microphone .IsRecording (null ))
{
return;
}
Microphone.End(null);
myAudioSource.Stop();
}
private void PlayRecord()
{
if (Microphone.IsRecording(null)) return;
if (myAudioSource.clip == null) return;
myAudioSource.mute = false;
myAudioSource.loop = false;
myAudioSource.Play();
}
private void PrintRecord()
{
if (Microphone.IsRecording(null)) return;
byte[] data = GetClipData();
string sLog = "total length " + data.Length + " time " + myAudioSource.time;
}
public byte[] GetClipData()
{
if (myAudioSource.clip == null) return null;
float[] samples = new float[myAudioSource.clip.samples];
myAudioSource.clip.GetData(samples, 0);
byte[] outData = new byte[samples.Length * 2];
int rescaleFator = 32767;
for (int i = 0; i < samples .Length ; i++)
{
short temshort = (short)(samples[i] * rescaleFator);
byte[] tempData = System.BitConverter.GetBytes(temshort);
outData[i * 2] = tempData[0];
outData[i * 2 + 1] = tempData[1];
}
if(outData == null || outData.Length <= 0)
{
return null;
}
return outData;
}
}