Unity常用音頻操作類示例代碼
下面通過代碼給大傢介紹Unity常用音頻操作類,具體代碼如下所示:
using UnityEngine; using System.Collections; public class AudioPlay : MonoBehaviour { public static AudioPlay Instance; public AudioClip[] FuChuAudio; public AudioSource FCAudio; // public AudioSource BabyAudio; // Use this for initialization void Awake() { Instance = this; } void Start () { } // Update is called once per frame void Update () { } /// <summary> /// 播放某個音頻 /// </summary> /// <param name="i"></param> public void playAudio(int i) { FCAudio.clip = FuChuAudio[i]; FCAudio.Play(); } /// <summary> /// 停止播放所有的音頻 /// </summary> public void StopplayAll() { for (int i= 0; i< FuChuAudio.Length; i++) { FCAudio.clip = FuChuAudio[i]; FCAudio.Stop(); } } /// <summary> /// 停止播放某個音頻 /// </summary> /// <param name="i"></param> public void StopplayOne(int i) { FCAudio.clip = FuChuAudio[i]; FCAudio.Stop(); } /// <summary> /// 循環播放某個音頻 /// </summary> /// <param name="i"></param> public void playLoop(int i) { FCAudio.clip = FuChuAudio[i]; FCAudio.loop = true;//設置聲音為循環播放 ; FCAudio.Play(); } }
/***將這個腳本掛載到一個空物體上,並且給它添加 AudioSource 組件*/using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 控制所有音樂的管理類 /// </summary> public class AudioManager : MonoBehaviour { //將要輪流播放的音樂組 public AudioClip[] audioGroup; //當前播放的是誰 private int playingIndex; //是否允許播放音樂 private bool canPlayAudio; //AudioSource組件 private AudioSource audioSource; //----------------------------------------------------- void Start() { audioSource = this.GetComponent<AudioSource>(); canPlayAudio = true; playingIndex = 0; } //----------------------------------------------------- void Update() { if (canPlayAudio) { PlayAudio(); canPlayAudio = false; } if (!audioSource.isPlaying) { playingIndex++; if (playingIndex >= audioGroup.Length) { playingIndex = 0; } canPlayAudio = true; } } //----------------------------------------------------- private void PlayAudio() { audioSource.clip = audioGroup[playingIndex]; audioSource.Play(); } //----------------------------------------------------- }
到此這篇關於Unity常用音頻操作類示例代碼的文章就介紹到這瞭,更多相關Unity音頻內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- 一文詳解Unity3D AudioSource組件使用示例
- 詳解Unity 實現語音識別功能
- 聊聊Unity自定義組件之序列幀播放組件問題
- Unity實現動物識別的示例代碼
- Unity接入百度AI實現果蔬識別