0

I want a sound player to play as long as a button is pressed.

Here is what I've done so far :

public partial class Form1 : Form
{
    private SoundPlayer soundPlayer;

    private void FormMain_KeyPress(object sender, KeyPressEventArgs e)        
    {
        if(e.KeyChar == 'n')
        { 
            SoundPlayer s = new SoundPlayer(@"C:\Users\darude_rig\Desktop\dayz sounboard\media\sounds\AKM.wav");
            s.PlayLooping();
        }
    }
}

Where is the problem and how can I fix it?

Steve Mitcham
  • 5,268
  • 1
  • 28
  • 56
darude_cod3r
  • 91
  • 3
  • 11
  • Do you get an error or just nothing happens? Are you sure the file path is correct? "dayz sounboard" is missing a "d", don't know if that is intentional. – Tyler Day Apr 02 '15 at 20:07
  • Please chck this out : http://stackoverflow.com/questions/16702659/play-a-sound-while-key-is-down – Saagar Elias Jacky Apr 02 '15 at 20:08
  • Are you sure about the path of the wav file or you have the enough rights to access that directory? – EZI Apr 02 '15 at 20:09
  • just nothing happens... and no the d is missing intentionaly – darude_cod3r Apr 02 '15 at 20:22
  • 1
    Have you tried using the debugger to make sure you're getting into the `if` statement block? Stepping through the code with the debugger and examining variable values should always be your first step (i.e. before posting it as a question on SO and expecting us to do the debugging for you). – Craig W. Apr 02 '15 at 21:30

1 Answers1

0

You might try initializing and/or looping the SoundPlayer instance in a KeyDown event, and then stopping it in a KeyUp event.

public partial class Form1 : Form
{
    private SoundPlayer soundPlayer;

    private void FormMain_KeyDown(object sender, KeyEventArgs e)        
    {
        if(e.KeyCode == Keys.N)
        { 
            if (soundPlayer == null)
                soundPlayer = new SoundPlayer(@"C:\Users\darude_rig\Desktop\dayz sounboard\media\sounds\AKM.wav");

            soundPlayer.PlayLooping();
        } 
    }

    private void FormMain_KeyUp(object sender, KeyEventArgs e)        
    { 
        if(e.KeyCode == Keys.N)
        { 
            if (soundPlayer != null)
                soundPlayer.Stop();
        }
    }
}

Remember to subscribe to the form KeyUp and KeyDown events somewhere.

Monroe Thomas
  • 4,962
  • 1
  • 17
  • 21