Playing 2 sounds together at same time

前端 未结 3 930
野趣味
野趣味 2021-01-05 02:18

Designing a game for any laptop:

I want to play 2 sounds at the same time! A background music and a sound when pressing on a button!

Using System.Media

相关标签:
3条回答
  • 2021-01-05 03:15

    You CANNOT play two sounds at once using SoundPlayer.

    SoundPlayer is using the native WINAPI PlaySound function to accomplish the task which has no support for playing simultaneous sounds. Creating multiple instances of SoundPlayer won't help.

    There are many options most of which involve implementing a lot of the low level API to window's native audio library or DirectSound (note neither are C# and require alot of interop code)

    The simplest option would be to depend on windows media player to play the audio for you.

    Add a reference to "C:\Windows\System32\wmp.dll"

    then use

    var player = new WMPLib.WindowsMediaPlayer();
    player.URL = @"..\..\bin\debug\tribal dance.wav";
    

    Note: play starts immediately after setting the URL property

    The down side of this approach is your reliance on media player for your application to work properly. On the upside, you can use any file format media player supports.

    0 讨论(0)
  • 2021-01-05 03:15

    Using (WMPLib) Windows Media Player Library you can do this easily. Keep Your file in Debug/Sound folder and follow the following code. This will run 2 file simultaneously. To Add WMPLib in your project add it by NuGet Package Manager.

     WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
     WMPLib.WindowsMediaPlayer wplayer2 = new WMPLib.WindowsMediaPlayer();     
     string play_string = "be.mp3";
     wplayer.URL = @"SOUND/" + play_string;
     wplayer.controls.play();
     string play_string2 = "ba.mp3";
     wplayer2.URL = @"SOUND/" + play_string2;
     wplayer2.controls.play();
    
    0 讨论(0)
  • 2021-01-05 03:23

    http://msdn.microsoft.com/en-us/library/dd562851%28v=VS.85%29.aspx this article may help If you need absolute path to file you can use next code

    string soundFile = Path.Combine(Directory.GetCurrentDirectory() + "file.wav");
    
    0 讨论(0)
提交回复
热议问题