c# - Unity 播放暂停音频效果不佳

标签 c# unity-game-engine audio

我无法找出通过单击按钮来播放和暂停音频源的正确代码。

这是我的代码

ButtonAction.GetComponent().onClick.AddListener(delegate
                     {
                         if (soundTarget.isPlaying)
                         {
                             soundTarget.Pause();
                         }
                         else if(!soundTarget.isPlaying)
                         {
                             soundTarget.Play();
                             playSound("sounds/English");
                         }
                     });

注意:默认情况下它不会播放,因为如果我默认播放它,它只会循环播放。它以某种方式工作,但我需要在播放或暂停之前多次单击该按钮。

帮助我。

最佳答案

很简单:

你的 Unity 场景应该是这样的:

enter image description here

对于我称为“UnityUI”的脚本,如下所示:

public AudioSource MyAudioSource;
public Button PlayBtn;
public PlayButtonText;

void Start()
{
    PlayBtn.onClick.AddListener(() =>
    {
        if (MyAudioSource.isPlaying)
        {
            MyAudioSource.Stop();
            PlayButtonText.text = "Play me!";
        }
        else
        {
            MyAudioSource.Play();
            PlayButtonText.text = "Stop me!";
        }
    });
}

希望这有帮助!

祝你编码愉快!

关于c# - Unity 播放暂停音频效果不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51923678/

相关文章:

c# - 将日期格式化为特定格式

python - 使用 Python PyAudio 播放 2 声道声音

带有泛型参数的 C# 8.0 可为空引用类型功能

c# - 无法加载或创建VS 2015.1。项目。无法创建Visual C#2015编译器

c# - CALDAV 编辑/删除 ICLOUD 中的多个事件

unity-game-engine - 基本旋转着色器 2D 拉动 Sprite 表中的其他 Sprite

unity-game-engine - Unity 变换.lookAt

mysql - 从统一数组中获取值: debug works,值正在改变,但颜色没有改变

ios:在主线程外播放声音

audio - 如何重现类似 C64 的声音?