2

I play mp3s and m4as with the following method:

private void playmp3(string path)
    {
        WMPLib.WindowsMediaPlayer a = new WMPLib.WindowsMediaPlayer();
        a.URL = path;
        a.controls.play();
    }

Usually when I play them, they only play for around 5 seconds or less and then stop playing. If i interact with the (WPF) form in any way, it also stops. I call playmp3 from a BackgroundWorker.

Edit: It actually stops playing about a tenth of a second after I move my mouse.

Wilson
  • 8,570
  • 20
  • 66
  • 101
  • Duplicate / Found a Useful Answer here : http://stackoverflow.com/questions/16922866/music-suddenly-stops-playing-in-application – Mehdi LAMRANI Feb 02 '17 at 03:54

2 Answers2

2

You need to also code in the player states like this.

Player = new WMPLib.WindowsMediaPlayer();
            Player.PlayStateChange +=
                new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(Player_PlayStateChange);
            Player.MediaError +=
                new WMPLib._WMPOCXEvents_MediaErrorEventHandler(Player_MediaError);
            Player.URL = "FC.wav";
            Player.controls.play();



   private void Player_PlayStateChange(int NewState)
   {
       if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsStopped)
       {

       }
   }

   private void Player_MediaError(object pMediaObject)
   {
       MessageBox.Show("Cannot play media file.");
       this.Close();
   }
krikara
  • 2,395
  • 10
  • 37
  • 71
1

in simple way. declare you player in class level.

 WMPLib.WindowsMediaPlayer a;

 private void playmp3(string path)
{
    a = new WMPLib.WindowsMediaPlayer();
    a.URL = path;
    a.controls.play();
}

in this way you can resolve the problem easily

if you using the same method to stop playing like that stuffs using a if condition in it like this

private void playmp3(string path)
{
     a = new WMPLib.WindowsMediaPlayer();
     a.URL = path;
     a.controls.play();
}

you need to add the new WMPLib.WindowsMediaPlayer(); also in the class level, other wise every time you call the method it create a new player instance and try to stop or play it so do it like this.

WMPLib.WindowsMediaPlayer a= new WMPLib.WindowsMediaPlayer();

private void playmp3(string path, string playState)
{

    a.URL = path;

    if(playstate.Equals("Play))
    {
    a.controls.play();
    }
    else if (playState.Equals("Stop"))
    {
      a.controls.stop();
    }
}