繁体   English   中英

同时播放两个声音c#

[英]Playing two sounds simultaneously c#

我正在创建一个WP7应用程序,需要在循环背景音乐上播放(按下按钮)各种声音效果。 通过按下按钮1启动背景音乐并循环播放。 当我按下按钮3(触发声音效果)时,首次按下时背景音乐上的声音效果会很好。 但是,当我再次按下按钮3时,背景音乐停止。 我无法弄清楚为什么会发生这种情况!? 我已粘贴下面的相关代码部分。 非常感谢任何帮助。

public partial class MainPage : PhoneApplicationPage
{
    SoundEffect soundEffect;
    Stream soundfile;

    // Constructor
    public MainPage()
    {
        InitializeComponent();
    }



    static protected void LoopClip(SoundEffect soundEffect)
    {
        {
        SoundEffectInstance instance = soundEffect.CreateInstance();
        instance.IsLooped = true;
        FrameworkDispatcher.Update();
        instance.Play();
        }
    }

    public void PlaySound(string soundFile)
    {
        using (var stream = TitleContainer.OpenStream(soundFile))
        {

            var effect = SoundEffect.FromStream(stream);
            effect.Play();
        }
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        soundfile = TitleContainer.OpenStream("BackgroundMusic.wav");
        soundEffect = SoundEffect.FromStream(soundfile);  
        LoopClip(soundEffect);
    }


    private void button3_Click(object sender, RoutedEventArgs e)
    {
        PlaySound("sound3.wav");
    }

}

}

如果您始终使用Instances,这应该有效,所以将代码更改为此,它应该清除问题:

public partial class MainPage : PhoneApplicationPage
{   

    SoundEffectInstance loopedSound = null;

    // Constructor
    public MainPage()
    {
        InitializeComponent();
    }

    static protected void LoopClip(SoundEffect soundEffect)
    {
        loopedSound = soundEffect.CreateInstance();
        loopedSound.IsLooped = true;
        loopedSound.Play();
    }

    public void PlaySound(string soundFile)
    {
        SoundEffect sound = SoundEffect.FromStream(Application.GetResourceStream(new Uri(soundFile, UriKind.Relative)).Stream);
        SoundEffectInstance instance = sound.CreateInstance();
        instance.Play();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        SoundEffect sound = SoundEffect.FromStream(Application.GetResourceStream(new Uri(@"BackgroundMusic.wav", UriKind.Relative)).Stream); 
        LoopClip(sound);
    }


    private void button3_Click(object sender, RoutedEventArgs e)
    {
        PlaySound("sound3.wav");
    }

}

上面的示例假设您的声音文件是使用Build Action = Content设置的,并且位于顶级目录中。

您需要从单独的线程播放每个声音。

这里似乎发生的是,不同的Play方法调用彼此干扰,因为它们在同一个线程中。

尝试将背景音乐放在一个单独的线程中,看看是否能解决您在问题中提到的问题。 如果是这样,也将其他人分开。

暂无
暂无

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

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