本文主要是介绍【Unity实战100例】Unity调取移动端的麦克风进行录音并播放传输字节,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
源工程地址: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转化为audioSourcepublic 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<BaseEventData> action){EventTrigger trigger = obj.GetComponent<EventTrigger>();if (trigger == null){trigger = obj.AddComponent<EventTrigger>();}if (trigger.triggers.Count == 0){trigger.triggers = new List<EventTrigger.Entry>();}UnityAction<BaseEventData> callback = new UnityAction<BaseEventData>(action);EventTrigger.Entry entry = new EventTrigger.Entry();entry.eventID = eventID;entry.callback.AddListener(callback);trigger.triggers.Add(entry);}
对应的ui组件挂靠一下直接运行工程就好了
3.运行结果
具体接下来想实现什么功能就可以自己更改自定义
这篇关于【Unity实战100例】Unity调取移动端的麦克风进行录音并播放传输字节的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!