Playing two sounds simultaneously c#

后端 未结 2 1533
-上瘾入骨i
-上瘾入骨i 2020-12-11 21:06

I am creating a WP7 application that requires various sound effects to be played (on button press) over looped background music. The background music is initiated by pressin

相关标签:
2条回答
  • 2020-12-11 21:15

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

    What seems to be happening here is that the different Play method calls are interfering with each other since they are in the same thread.

    Try just putting the background music in a separate thread and see if that solves the problem you mention in the question. If so, split the others out as well.

    0 讨论(0)
  • 2020-12-11 21:34

    This should work if you are always working with Instances so change your code to this and it should clear up 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 your sound files are set with Build Action = Content and are in the top level directory.

    0 讨论(0)
提交回复
热议问题