4

I am trying to play a typing sound every time a key is pressed, using the SoundPlayer class (to simulate typewriter sounds).

public void MyKeyDown(object sender, KeyEventArgs)
{
    player = new System.Media.SoundPlayer(@"f:\sounds\2.wav");
    player.Play();
}

It works fine... as long as you type around 20 words per minute. Any faster than that and the sounds aren't played in full or even stop playing completely until you slow down

2.wav is a 8kb sound file with a duration of 0.1 seconds, so based on the sound duration alone, the file could be played in full 600 times per minute (enough for a typing speed of about 90 wpm).

Is there any faster way to play a sound file, or is the problem somewhere else?

Sylverdrag
  • 8,560
  • 5
  • 32
  • 49
  • 5
    Nobody types at a steady clip. SoundPlayer is very simplistic, it has no option to overlap or mix sounds. Look at the NAudio library for example. – Hans Passant Jun 02 '19 at 15:31
  • Would it be quicker to have a single instance of the player? And simply call play each time? – the.Doc Jun 02 '19 at 15:45
  • @the.Doc Tried it both ways and it makes no difference. – Sylverdrag Jun 02 '19 at 16:02
  • @HansPassant I just tried playback with NAudio and code from a tutorial. Works a bit better, but crashes after a short while, despite being inside "try" block. I'll have a closer look to see if I can make it work, and ask a better question if I can't. – Sylverdrag Jun 02 '19 at 16:32

1 Answers1

0

The way you do it you will create a new instance of SoundPlayer on every KeyDown, which will then need to reload the same sample from disc every time. The SoundPlayer class has an constructor which takes the location of the sound file as argument. In this case you can reuse the SoundPlayer instance and the file is cached in memory. I can imagine this is way faster.

Something like this should do the trick:

private SoundPlayer soundPlayer;

// Call this on App Startup / Initialization...
private void InitializeSoundPlayer() 
{
  this.soundPlayer = new SoundPlayer("sound.wav");
}

public void MyKeyDown(object sender, KeyEventArgs)
{
    this.soundPlayer.Play();
}

In my case this was working more fluent.

feal
  • 466
  • 4
  • 9