Play two sounds simultaneusly

前端 未结 6 1140
时光取名叫无心
时光取名叫无心 2020-11-27 05:09

Is there a way to play two sounds at the same time?

I know that SoundPlayer isn\'t able to do this. I can\'t use SoundEffect as I believe i

6条回答
  •  再見小時候
    2020-11-27 06:01

    Reference PresentationCore and WindowsBase and try this...

    var p1 = new System.Windows.Media.MediaPlayer();
    p1.Open(new System.Uri(@"C:\windows\media\tada.wav"));
    p1.Play();
    
    // this sleep is here just so you can distinguish the two sounds playing simultaneously
    System.Threading.Thread.Sleep(500);
    
    var p2 = new System.Windows.Media.MediaPlayer();
    p2.Open(new System.Uri(@"C:\windows\media\tada.wav"));
    p2.Play();
    

    EDIT I received a downvote probably because at first glance this looks like it will play the second sound after the first is finished. It doesn't, they are played by windows asynchronously. The sleep is there so if you test this code verbatim you can hear the sounds play together, it wouldn't be noticeable without the delay since they are the same sound.

    This code demonstrates the two sounds playing on separate threads on top of each other, which is sort of pointless since the playback doesn't block anyway

    new System.Threading.Thread(() => {
            var c = new System.Windows.Media.MediaPlayer();
            c.Open(new System.Uri(@"C:\windows\media\tada.wav"));
            c.Play();
        }).Start();
    
    System.Threading.Thread.Sleep(500);
    
    new System.Threading.Thread(() => {
            var c = new System.Windows.Media.MediaPlayer();
            c.Open(new System.Uri(@"C:\windows\media\tada.wav"));
            c.Play();
        }).Start();
    

    http://msdn.microsoft.com/en-us/library/system.windows.media.mediaplayer.stop.aspx The class also has the control you need to stop playback

提交回复
热议问题