使用Unity原生方法进行录音即使播放基于UGUI

因为要做类似于微信语音聊天的功能,所以要使用原生的方法进行录音然后转播,看了下论坛和博客,发现了几个方法,随后整理了一下,写了这么个脚本。

首先,在Unity里面先新建一个Butten作为录音的按钮,最终实现功能按下的时候开始录音,松开录音结束,随后播放,话不多说,直接上代码,我这里使用了两个接口IPointerDownHandler和IPointerUpHandler,继承接口之后就可以实现按下录音松开结束的功能。

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class VoiceChat : MonoBehaviour,IPointerDownHandler, IPointerUpHandler
{
    float timer = 60;
    public AudioSource aud;
    public GameObject VoiceChatUI;
    public Text ShowUI;
    void Start()
    {    
        VoiceChatUI.SetActive(false);
    }
    public void OnPointerDown(PointerEventData eventData)
    {
        VoiceChatUI.SetActive(true);
        StartCoroutine("KeepTime");
        aud.clip = Microphone.Start("Built-in Microphone", false, 60, 44100);
    }
    public void OnPointerUp(PointerEventData eventData)
    {
        Microphone.End("Built-in Microphone");
        VoiceChatUI.SetActive(false);
        StopCoroutine("KeepTime");
        Debug.Log("停止");
        aud.Play();
    }
    IEnumerator KeepTime()
    {
        int ShowTimeUI;
        yield return new WaitForSeconds(0f);
        for (float timer=60;timer>=0;timer-=Time.deltaTime)
        {
            if (timer<=60)
            {
                ShowTimeUI = (int)timer+1;
                ShowUI.text = ShowTimeUI.ToString() + "秒"; 
            }
            yield return 0; 
        }
    }
}
在Unity里面建一个 AudioSource,一个Text作为显示,一个Image作为展示拉倒对应的槽里面,在这样就可以轻松实现录音了!

脚本在这了,去试一下吧,Good Luck!

猜你喜欢

转载自blog.csdn.net/Superficialtise/article/details/69942593
今日推荐