System.Windows.Media.MediaPlayer playing sound twice

977 views Asked by At

I have a basic Windows Forms application that uses System.Windows.Media.MediaPlayer to play an MP3 file. The main form has a single button that opens a second form.

Main Form

The second form has a single button that plays 3 seconds of an MP3 file.

Second Form

Everything works correctly the first time that I open the second form and click the Play button. But if I close the second form and then re-open it, the MP3 play behaves erratically. Usually it plays the sound twice. Sometimes it plays the sound after a several second delay.

As you can see from the screenshots, I am running the application in Windows XP. I have also tried running it on a Windows 10 machine and there the issue does not occur. Any assistance in identifying the cause of this behavior would be greatly appreciated.

Here is the code for the second form which plays the MP3 file:

public partial class SecondForm : Form
{
    public SecondForm()
    {
        InitializeComponent();
    }

    private string _tone = Path.Combine("Resources", "beep-17.mp3");
    private int _toneDuration = 3000;

    System.Windows.Media.MediaPlayer _mediaPlayer = new System.Windows.Media.MediaPlayer();

    private void PlayMP3Form_Load(object sender, EventArgs e)
    {
        string mp3Path = Path.GetFullPath(_tone);
        Uri mp3File = new Uri(mp3Path);

        _mediaPlayer.Open(new Uri(mp3File.AbsoluteUri));
    }

    private void buttonPlay_Click(object sender, EventArgs e)
    {
        _mediaPlayer.Position = TimeSpan.FromMilliseconds(_mediaPlayer.NaturalDuration.TimeSpan.TotalMilliseconds - _toneDuration);
        _mediaPlayer.Play();
    }

}
1

There are 1 answers

0
Elijah Holt On

In case anyone else runs into this same issue, I have found a solution that seems to work for me. I've added a call to close the MediaPlayer object when the second form is closed:

    private void SecondForm_FormClosed(object sender, FormClosedEventArgs e)
    {
        _mediaPlayer.Close();
    }

This prevents the duplicate tone playback behavior that I was seeing previously when I would re-open the second form.