简体   繁体   English

如何统一循环播放音频?

[英]How to loop an audio in unity?

I was writing a game project on Unity and stumbled with inability to make an audio play infinitely in main menu.我正在 Unity 上编写一个游戏项目,并且偶然发现无法在主菜单中无限播放音频。

The problem is that the track is played only once (while staying in the menu), when I need it to be repeating until player leaves the menu.问题是该曲目仅播放一次(同时停留在菜单中),当我需要重复播放直到播放器离开菜单时。

Here is the part of the code where I enable music.这是我启用音乐的代码部分。 I use AudioClip and AudioSource for this.为此,我使用 AudioClip 和 AudioSource。

public AudioClip menu;
private AudioSource audio;

void Start() {
        ...
        audio = GetComponent<AudioSource>();
        audio.loop = true;
        audio.PlayOneShot(menu);
        ...
}
public AudioClip menu;
private AudioSource Audio;

void Start()
{
    Audio = GetComponent<AudioSource>();
    Audio.clip = menu;
    Audio.loop = true;
    Audio.Play();
}

If you check Loop option in the AudioSource component in the editor, it should work.如果您在编辑器的 AudioSource 组件中选中 Loop 选项,它应该可以工作。 If not, you messed something up.如果没有,你把事情搞砸了。 There is an another way tho, you can loop it like this.还有另一种方式,你可以像这样循环它。

private AudioSource audio;

    void Start()
    {

        StartCoroutine(LoopAudio());
    }

    IEnumerator LoopAudio()
    {
        audio = GetComponent<AudioSource>();
        float length = audio.clip.length;

        while(true)
        {
            audio.Play();
            yield return new WaitForSeconds(length);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM