Unity播放列表按顺序排列

问题描述 投票:0回答:2

我有一个播放列表可以随机播放歌曲,但是我想要按顺序播放它们或者播放它们。任何帮助将不胜感激 :)

公共课音乐:MonoBehaviour {

public AudioClip[] clips;
private AudioSource audiosource;

void Start()
{
    audiosource = FindObjectOfType<AudioSource>();
    audiosource.loop = false;
}

void Update()
{
    if(!audiosource.isPlaying)
    {

        audiosource.clip = GetRandomClip();
        audiosource.Play();
    }
}

private AudioClip GetRandomClip()
{
    return clips[Random.Range(0, clips.Length)];
}

private void Awake()
{
    DontDestroyOnLoad(transform.gameObject);
}

}

unity5 audio-player
2个回答
0
投票

我没有得到你的问题,是不是就这么简单?

public class Music : MonoBehaviour 
{
    public AudioClip[] clips;
    private AudioSource audiosource;
    public bool randomPlay = false;
    private int currentClipIndex = 0;

    void Start()
    {
        audiosource = FindObjectOfType<AudioSource>();
        audiosource.loop = false;
    }

    void Update()
    {
        if(!audiosource.isPlaying)
        {
            AudioClip nextClip;
            if (randomPlay)
            {
                nextClip = GetRandomClip();
            }
            else
            {
                nextClip = GetNextClip();
            }
            currentClipIndex = clips.IndexOf(nextClip);
            audiosource.clip = nextClip;
            audiosource.Play();
        }
    }

    private AudioClip GetRandomClip()
    {
        return clips[Random.Range(0, clips.Length)];
    }

    private AudioClip GetNextClip()
    {
        return clips[(currentClipIndex + 1) % clips.Length)];
    }

    private void Awake()
    {
        DontDestroyOnLoad(transform.gameObject);
    }
}

0
投票

之前的答案没有用。它返回了几个错误。我修改了您的脚本并使用Unity 2018.2.12f1对其进行了测试。

这应该添加到具有音频源组件的空游戏对象。将音频剪辑拖放到剪辑字段以创建列表。

public bool randomPlay = false; // checkbox for random play
public AudioClip[] clips;
private AudioSource audioSource;
int clipOrder = 0; // for ordered playlist

void Start () {
    audioSource = GetComponent<AudioSource> ();
    audioSource.loop = false;
}

void Update () {
    if (!audioSource.isPlaying) {
        // if random play is selected
        if (randomPlay == true) {
            audioSource.clip = GetRandomClip ();
            audioSource.Play ();
            // if random play is not selected
        } else {
            audioSource.clip = GetNextClip ();
            audioSource.Play ();
        }
    }
}

// function to get a random clip
private AudioClip GetRandomClip () {
    return clips[Random.Range (0, clips.Length)];
}

// function to get the next clip in order, then repeat from the beginning of the list.
private AudioClip GetNextClip () {
    if (clipOrder >= clips.Length - 1) {
        clipOrder = 0;
    } else {
        clipOrder += 1;
    }
    return clips[clipOrder];
}

void Awake () {
    DontDestroyOnLoad (transform.gameObject);
}
© www.soinside.com 2019 - 2024. All rights reserved.