Play two sounds simultaneously C #

I am creating a WP7 application that requires playing various sound effects (at the touch of a button) over looped background music. Background music starts by pressing button 1, and the loops are in order. When I press button 3 (causes a sound effect), when I press it for the first time, the sound effect is superimposed on the background music. However, when I press button 3 again, the background music stops. I can’t understand why this can happen !? I have inserted the relevant parts of the code below. Would thank for any help.

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"); } } 

}

+4
source share
2 answers

This should work if you always work with instances, so change your code to this and it should fix the problem:

 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"); } } 

The above example assumes that your sound files are set using Action Action = Content and are in the top-level directory.

+4
source

You will need to play each sound from a separate stream.

What is happening here is that different calls to the Play methods interfere with each other because they are on the same thread.

Try just putting background music in a separate stream and see if this solves the problem you mentioned in the question. If so, divide the rest.

0
source

Source: https://habr.com/ru/post/917685/


All Articles