您当前的位置: 首页 >  unity

幻世界

暂无认证

  • 2浏览

    0关注

    237博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Unity调取移动端的麦克风进行录音并播放传输字节

幻世界 发布时间:2018-03-27 14:20:46 ,浏览量:2

源工程地址: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.运行结果

具体接下来想实现什么功能就可以自己更改自定义

关注
打赏
1660704426
查看更多评论
立即登录/注册

微信扫码登录

0.0384s