首页 文章

使用多个按钮播放多个声音

提问于
浏览
-2

如何让多个按钮一次播放不同的声音,并使用 Windows Phone XNA 框架有一个共同的停止按钮?当播放声音时,它应播放循环,直到有人按下停止按钮或按下另一个按钮。

我使用SoundEffectCreateInstance的方式,它循环播放并且播放正常但是当单击第二个按钮时,第二个声音开始与第一个一起播放。还需要帮助创建公共停止按钮。非常感谢提前。

我为每个按钮尝试了类似下面的东西。

private void button2_Click(object sender, RoutedEventArgs e)
{
    var stream = TitleContainer.OpenStream("Sounds/A3.wav");
    var effect = SoundEffect.FromStream(stream);
    SoundEffectInstance instance = effect.CreateInstance();
    instance.IsLooped = true;
    instance.Play();

但由于创建的实例不在 program-wide 级别,因此我无法创建常用的停止按钮。

我是编程的初学者。谢谢你的理解。

1 回答

  • 0

    您可以向类和一些辅助方法添加成员变量:

    public class YourClass
    {
        private SoundEffectInstance currentSoundEffect = null;
    
        private void StopCurrentSoundEffect()
        {
            this.currentSoundEffect.Stop();
            this.currentSoundEffect = null;
        }
    
        private void PlaySoundEffect(string fileName)
        {
            this.StopCurrentSoundEffect();
            using (var stream = TitleContainer.OpenStream("Sounds/A3.wav"))
            {
                var soundEffect = SoundEffect.FromStream(stream);
                this.currentSoundEffect = soundEffect.CreateInstance();
                this.currentSoundEffect.IsLooped = true;
                this.currentSoundEffect.Play();
            }
        }
    }
    

    现在,每个事件处理程序都可以使用所需的文件名调用this.PlaySoundEffect

相关问题