0

I'm creating a virtual piano keyboard using c#, but I have a big problem with the sounds.

For each key I press on the pc's keyboard, this is the code:

private void Form1_KeyDown(object sender, KeyPressEventArgs e)
{
    [...]   // Other code
    animation(key, name);
}

private void animation(object sender, string name)
{
    [...]   // Other code
    play(keyName);
}

private void play(string keyName)
{
    [...]   // Other code
    string path = Application.StartupPath + "\\sounds\\" + keyName + ".wav";
    var sound = new System.Media.SoundPlayer(path);

    sound.Play();
}

The problem is that with this code I can just press one key (so also just one sound) and this is not realistic. How can I solve this problem? Maybe using threads? How?

Thank'you so much!

Poppo
  • 21
  • 5
  • You're playing sound in UI thread, so until sond play finishes, no key events will be processed. You have to play sound in background thread. – Andrey Korneyev May 31 '17 at 08:45
  • How con i do it? – Poppo May 31 '17 at 08:51
  • wrapping code from `play` method inside a `Task.Run(()=>{//code here})` will help, i think. but don't await it – Alex May 31 '17 at 08:51
  • 1
    @Alex that's what Play already does. It uses a separate thread. The problem isn't threading, it's the use of SoundPlayer. That's just a proxy for ... SoundPlayer. It's not a sound API. One SoundPlayer control can only play one file at a time. Multiple players will play multiple files without any kind of synchronization. One player can play a multi-channel file. – Panagiotis Kanavos May 31 '17 at 08:55
  • @Poppo if you want an Audio API, use a library like [NAudio](https://github.com/naudio/NAudio). SoundPlayer is just a proxy for the SoundPlayer control, whose job is to play files. – Panagiotis Kanavos May 31 '17 at 08:57
  • A quick&dirty way to play multiple files would be to create multiple SoundPlayer objects and `Load` a wav into them. Each time a key is pressed, call `Play` on the appropriate player. You can store the players on a dictionary using the key name as key. Not the most efficient way but works for simple cases – Panagiotis Kanavos May 31 '17 at 09:09
  • Take a look [here](https://stackoverflow.com/questions/6240002/play-two-sounds-simultaneusly). `SoundPlayer` seems unable to play multiple sounds, you need `MediaPlayer`. I guess this also makes your question a duplicate, which should be closed. – r41n May 31 '17 at 14:43

0 Answers0