源工程地址:https://download.csdn.net/download/qq_37310110/11869058
1.对MicroPhone类的理解
对麦克风的调用在Unity里主要是用到了MicroPhone这个类,此类里面有几个方法可以方便我们实现功能
2.获取麦克风设备 devices = Microphone.devices;
if (devices.Length != 0)
{
ShowTimeHint.text = "设备有麦克风:" + devices[0];
}
else
{
ShowTimeHint.text = "设备没有麦克风";
}
3.开始录音
AddTriggersListener(voiceBtn.gameObject, EventTriggerType.PointerDown, (t) =>
{
Debug.Log("开始说话");
StartCoroutine("KeepTime");
//参数一:设备名字,null为默认设备;参数二:是否循环录制;参数三:录制时间(秒);参数四:音频率
aud.clip = Microphone.Start(devices[0], false, 15, 6000);
});
4.结束录音
AddTriggersListener(voiceBtn.gameObject, EventTriggerType.PointerUp, (t) =>
{
Debug.Log("结束说话");
StopCoroutine("KeepTime");
Microphone.End(devices[0]);
//直接播放
aud.Play();
string byteStr = AudioToByte(aud);
//传输给服务器
//GameManager.GetInstance.tcpClient.SendMeToServer(ProtoType.T_S_Voice, byteStr);
});
5. 音频字节相互转换
//把录好的音段转化为base64的string。测试过不转base64直接用byte[]也是可以的
public string AudioToByte(AudioSource audio)
{
float[] floatData = new float[audio.clip.samples * audio.clip.channels];
audio.clip.GetData(floatData, 0);
byte[] outData = new byte[floatData.Length];
Buffer.BlockCopy(floatData, 0, outData, 0, outData.Length);
return Convert.ToBase64String(outData);
}
//把base64的string转化为audioSource
public void ByteToAudio(AudioSource audioSource, string str)
{
byte[] bytes = Convert.FromBase64String(str);
float[] samples = new float[bytes.Length];
Buffer.BlockCopy(bytes, 0, samples, 0, bytes.Length);
audioSource.clip = AudioClip.Create("RecordClip", samples.Length, 1, 6000, false);
audioSource.clip.SetData(samples, 0);
audioSource.Play();
}
6.添加按钮监听类型事件
//添加按钮监听类型
private void AddTriggersListener(GameObject obj, EventTriggerType eventID, UnityAction action)
{
EventTrigger trigger = obj.GetComponent();
if (trigger == null)
{
trigger = obj.AddComponent();
}
if (trigger.triggers.Count == 0)
{
trigger.triggers = new List();
}
UnityAction callback = new UnityAction(action);
EventTrigger.Entry entry = new EventTrigger.Entry();
entry.eventID = eventID;
entry.callback.AddListener(callback);
trigger.triggers.Add(entry);
}
对应的ui组件挂靠一下直接运行工程就好了
3.运行结果具体接下来想实现什么功能就可以自己更改自定义