Play multiple sounds using SoundPlayer

后端 未结 6 490
清酒与你
清酒与你 2020-11-27 22:12

I\'m making a sampler program where each key from 1 to 9 will make a different sound. Everything works fine, but when I press two (or more) sounds at the same time, the seco

6条回答
  •  自闭症患者
    2020-11-27 22:45

    There is one simple way to play multiple sounds at once in C# or VB.Net. You will have to call the mciSendString() API Function to play each .wav file. You won't even have to do multi-threading, unless you are loop-playing. Here is a complete working example of a MusicPlayer class created using mciSendString().

    // Sound api functions
    [DllImport("winmm.dll")]
    static extern Int32 mciSendString(string command, StringBuilder buffer, int bufferSize, IntPtr hwndCallback);
    

    In the above function, the key is first parameter command. As long as you call two functions with a separate command name, they will play separately/simultaneously. This is what I did in one of my C# programs:

    private void PlayWorker()
    {
        StringBuilder sb = new StringBuilder();
        mciSendString("open \"" + FileName + "\" alias " + this.TrackName, sb, 0, IntPtr.Zero);
        mciSendString("play " + this.TrackName, sb, 0, IntPtr.Zero);
        IsBeingPlayed = true;
    }
    

    EDIT: Added link to a working example.

提交回复
热议问题