How do I pause or stop an audio file, which is being played

Viewed 1642

The button click method mentioned below, can be used to start playing an audio file. However, once it starts it cannot be paused, if I click the button again the song will start to play again, from the beginning. Please let me know the way to stop it using Enter Key.

private void btn_reproducir_Click(object sender, EventArgs e)
{         
    WindowsMediaPlayer myplayer = new WindowsMediaPlayer();
    myplayer.URL = @"C:\song.mp3";
    myplayer.controls.play();
}
2 Answers

Please try this code.

public partial class Form1 : Form
    {
        // Media player object
        WindowsMediaPlayer myplayer = new WindowsMediaPlayer();        

        public Form1()
        {
            InitializeComponent();
            myplayer.URL = @"C:\song.mp3";
        }

        private void reproducir_Click(object sender, EventArgs e)
        {           
            myplayer.controls.play();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            myplayer.controls.stop();
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
             myplayer.controls.pause();
        }
    }

If you want to use the same button to play and pause the music, you can use a flag to determine its behavior:

bool isPlaying = false;

private void btn_reproducir_Click(object sender, EventArgs e)
{         
    WindowsMediaPlayer myplayer = new WindowsMediaPlayer();
    myplayer.URL = @"C:\song.mp3";

    if(isPlaying)
    {
        myplayer.controls.pause();
        isPlaying = false;
    }
    else
    {
        myplayer.controls.play();
        isPlaying = true;
    }
}

If you want to use the enter key to click the button from anywhere in the form, simply set the form's "AcceptButton" to the button you want clicked. As long as the control that currently has focus does not use the enter key, then pressing the enter key will automatically click the AcceptButton. A scenario where this would not work would be if a multi-line text box has focus. A multi-line text box allows you to press enter to start a new line, so the AcceptButton would not be clicked in this case.

enter image description here

Additionally, you can always use the tab key to tab to the button and then press enter once the button is highlighted.

Related