音效系统

音频文件的导入

常用格式 wav mp3 ogg aiff/aif

音源 Audio Source

Spatial Blend 音频受3D空间的影响程度

音频监听脚本 Audio Listener


代码控制音源播放

public class Lesson20 : MonoBehaviour
{
    AudioSource audioSource;
    public GameObject gobj;
    public AudioClip aClip;
    // Start is called before the first frame update
    void Start()
    {
        audioSource = GetComponent<AudioSource>();

    }

    // Update is called once per frame
    void Update()
    {
        #region 代码控制播放和停止
        //按键播放
        if (Input.GetKeyDown(KeyCode.P))
        {
            audioSource.Play();
        }
        //按键停止
        if (Input.GetKeyDown(KeyCode.P))
        {
            audioSource.Stop();
        }
        if (Input.GetKeyDown(KeyCode.Space))
        {
            audioSource.Pause();
        }
        #endregion

        #region 检测音频源播放完毕
        if (audioSource.isPlaying)
        {
            print("Playing");
        }
        else
        {
            print("End");
        }
        #endregion

        #region 动态控制音效播放
        //直接在要播放音效的对象上挂载脚本去控制播放

        //实例化挂载了音效源的脚本
        Instantiate(gobj);

        //用一个AudioSource来控制播放不同的音效
        AudioSource aus = gameObject.AddComponent<AudioSource>();
        aus.clip = aClip;
        aus.Play();
        #endregion
    }
}

麦克风相关

public class Lesson21 : MonoBehaviour
{
    AudioClip myClip;
    // Start is called before the first frame update
    void Start()
    {
        #region 获取麦克风信息
        string[] strs = Microphone.devices;
        for (int i = 0; i < strs.Length; i++)
        {
            print(strs[i]);
        }
        #endregion

    }

    // Update is called once per frame
    void Update()
    {
        #region 开始录制
        //参数一 设备名 传空使用默认设备
        //参数二 超过录制长度后是否重新录制
        //录制时长
        //采样率
        if(Input.GetKeyDown(KeyCode.Space))
        {
            myClip = Microphone.Start(null, false, 10, 44100);
        }
        #endregion

        #region 结束录制
        if (Input.GetKeyUp(KeyCode.Space))
        {
            Microphone.End(null);
            AudioSource s = GetComponent<AudioSource>();
            if (s == null) 
                s = gameObject.AddComponent<AudioSource>();
            s.clip = myClip;
            s.Play();

            #region 存储和传输录制的音效数据
            //数组长度规则固定是声道数*剪辑长度
            float[] f = new float[myClip.channels*myClip.samples];
            myClip.GetData(f, 0);
            #endregion
        }
        #endregion
    }
}

posted @ 2025-03-17 15:31  cannedmint  阅读(9)  评论(0)    收藏  举报