Unity3D播放音频数组的问题

今天工作中遇到了一个问题,unity3d中加载了一个音频数组 audioclip[],怎么依次播放这个音频数组.目前想到了三种方案,写下来一起看看,有什么不足请指出和改进
源码如下:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class AnimManager : MonoBehaviour {


    private AudioSource myAudioSource;

    private string resourcePath;

    private UnityEngine.Object[] resObjs;

    private AudioClip[] audios;

    // Use this for initialization
    void Start () {

       if (myAudioSource == null)
        {
            myAudioSource = this.gameObject.AddComponent();
        }
        resToAudios();

    }

     //根据输入索引播放音频  这是第二种方案的方法
     #region第二种
     private void PlayAudio(int index)
     {
        //这里为了程序严谨需要做一个index的判断,我懒得写了.  
         myAudioSource.clip = null;

        myAudioSource.clip = audios[index];

        myAudioSource.Play();

       // myAudioSource.PlayOneShot(audios[index]);

         myAudioSource.loop = false;

        currentIndex++;
     }

    //一个临时索引
    private int currentIndex = 0;
    //播放的方法
    public void PlayAudio()
    {
        if (!myAudioSource.isPlaying)
        {
            PlayAudio(currentIndex);
        }
    }
     //void Update()
    //{
    //    PlayAudio();
    //}
    #endregion

    //在resources路径下加载资源,这里只是做一个resources路径下的演示,具体的加载资源的方式不在此处讨论.
    private void LoadAllAudios()
    {
        resourcePath = SceneManager.GetActiveScene().name;
        resObjs = Resources.LoadAll(resourcePath,typeof(AudioClip));
    }
   //将加载出来的资源obj转换成为想获取的audioclip类型,此处最好写为泛型,具体方式不赘述.
    private void resToAudios()
    {
        LoadAllAudios();
        audios = new AudioClip[resObjs.Length];
        for (int i = 0; i < resObjs.Length; i++)
        {

            audios[i] = resObjs[i] as AudioClip;
        }
    }

    //这是第一种方式,用协程加载,
    #region
    IEnumerator IEPlayAudio(int index)
    {
        if (index >= audios.Length)
        {
            index = audios.Length - 1;
        }
        currentIndex = index;

        myAudioSource.clip = null;

        myAudioSource.clip = audios[currentIndex];

        myAudioSource.Play();

        // myAudioSource.PlayOneShot(audios[index]);

        myAudioSource.loop = false;

        yield return new WaitForSeconds(myAudioSource.clip.length);

        currentIndex++;
        if (currentIndex != audios.Length)
        {
           //递归   播放
            StartCoroutine(IEPlayAudio(currentIndex));
        }
        else
        {
            StopAllCoroutines();
        }
    }



    public void SelectedAudio(int index)
    {
        StopAllCoroutines();
        StartCoroutine(IEPlayAudio(index));
    }
    #endregion
}

第三种方式就是通过读配置表的方式了,需要填写配置表,做一个计时器,或者获取动画播放的帧数,第几帧或者第几秒播放那个音频..读表方式很多种,此处也不再赘述,有疑问可以Q我599580970.

你可能感兴趣的:(Unity学习经验)