Home > Blockchain >  WMPLib Music plays but when I switch tabs it stops
WMPLib Music plays but when I switch tabs it stops

Time:10-18

I have C# application for a Food Truck. I have some music playing when customers view the menu. On the menu form I have four tabs. I have the WMPLib code in form load. When the form loads the music begins playing however when I switch to a different tab the music stops. I have debugged but there is nothing there to really see since it runs the lines but just stops when you switch tabs. Any ideas on how to keep the music playing when switching tabs on the main form. I would like it to play continuous not just start again on each tab. Thanks. Here is an image of the form with the tabs.

enter image description here

Here is the form load code:

try
{
    WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();

    wplayer.URL = "runningdownadream.mp3";
    wplayer.settings.setMode("loop", true);
    wplayer.controls.play();
}
catch (Exception ex)
{
    MessageBox.Show("No music. Windows Media Player not installed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

CodePudding user response:

In order to play an MP3 in the background using WMPLib, try the following:

Create a class (name: HelperMp3.cs)

HelperMp3.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AxWMPLib;
using System.Diagnostics;

namespace WmpLibTest
{
    public class HelperMp3 : IDisposable
    {
        public delegate void EventHandlerMediaError(object sender, object pMediaObject);
        public delegate void EventHandlerPlayStateChanged(object sender, int newValue);

        //events
        public event EventHandlerMediaError Mp3MediaError;
        public event EventHandlerPlayStateChanged Mp3PlayStateChanged;

        public string MP3Filename { get; set; } //fully-qualified MP3 filename

        private WMPLib.WindowsMediaPlayer _wplayer = new WMPLib.WindowsMediaPlayer();

        public HelperMp3()
        {
            //subscribe to events (add event handlers)
            _wplayer.PlayStateChange  = _wplayer_PlayStateChange;
            _wplayer.MediaError  = _wplayer_MediaError;
        }

        private void _wplayer_MediaError(object pMediaObject)
        {
            System.Diagnostics.Debug.WriteLine("Error (MediaError): "   pMediaObject.ToString());

            //if subscribed to event, raise event, otherwise throw exception
            if (Mp3MediaError != null)
            {
                //raise event
                Mp3MediaError(this, pMediaObject);
            }
            else
            {
                throw new Exception("Error (MediaError): "   pMediaObject.ToString());
            }
        }

        private void _wplayer_PlayStateChange(int NewState)
        {
            //Undefined = 0,
            //Stopped = 1,
            //Paused = 2,
            //Playing = 3,
            //ScanForward = 4,
            //ScanReverse = 5,
            //Buffering = 6,
            //Waiting = 7,
            //MediaEnded = 8,
            //Transitioning = 9,
            //Ready = 10,
            //Reconnecting = 11,
            //Last = 12

            if (Mp3PlayStateChanged != null)
            {
                //raise event
                Mp3PlayStateChanged(this, NewState);
            }

            System.Diagnostics.Debug.WriteLine("_wplayer_PlayStateChange: "   NewState.ToString());
        }

        public void Dispose()
        {
            if (_wplayer != null)
            {
                _wplayer.controls.stop();

                //unsubscribe from events (add event handlers)
                _wplayer.PlayStateChange -= _wplayer_PlayStateChange;
                _wplayer.MediaError -= _wplayer_MediaError;

                //release all resources
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_wplayer);

                _wplayer = null;
            }
        }


        public void Start()
        {
            if (_wplayer != null)
            {
                _wplayer.controls.play();
            }
        }

        public void Stop()
        {
            if (_wplayer != null)
            {
                _wplayer.controls.stop();
            }
        }

        public void PlayMp3()
        {
            Debug.WriteLine("MP3Filename: "   MP3Filename);

            if (String.IsNullOrEmpty(MP3Filename) || !System.IO.File.Exists(MP3Filename))
            {
                throw new Exception("MP3Filename not specified.");
            }

            Debug.WriteLine("Playing mp3...");

            //set value
            _wplayer.URL = MP3Filename;
            _wplayer.settings.setMode("loop", true);

            _wplayer.controls.play();

        }
    }
}

In the form (ex: Form1) code, create an instance of the class above:

 private HelperMp3 _helperMp3 = new HelperMp3();

Then create a method that starts the music:

private void StartMusic(string mp3Filename)
{    
    //set property
    helperMp3.MP3Filename = mp3Filename;

    Task t1 = Task.Run(_helperMp3.PlayMp3);
}

Subscribe to the Load event for the form (ex: Form1_Load) and add the following code:

private void Form1_Load(object sender, EventArgs e)
{
    //ToDo: replace with your MP3 filename
    StartMusic(@"C:\Temp\Test.mp3");
}

Subscribe to the FormClosed event for the form (ex: Form1_FormClosed) and add the following code:

Form1_FormClosed

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
    if (_helperMp3 != null)
    {
        _helperMp3.Dispose();
        _helperMp3 = null;
    }
}

Alternatively, one can use BackgroundWorker. If using BackgroundWorker, in HelperMp3.cs change method PlayMp3 to the following:

public void PlayMp3(System.ComponentModel.BackgroundWorker worker, System.ComponentModel.DoWorkEventArgs e)
{
    Debug.WriteLine("MP3Filename: "   MP3Filename);

    if (String.IsNullOrEmpty(MP3Filename) || !System.IO.File.Exists(MP3Filename))
    {
        throw new Exception("MP3Filename not specified.");
    }

    if (worker.CancellationPending || e.Cancel)
    {
        e.Cancel = true;
    }

    Debug.WriteLine("Playing mp3...");

    //set value
    _wplayer.URL = MP3Filename;
    _wplayer.settings.setMode("loop", true);

    _wplayer.controls.play();

}

Note: If using BackgroundWorker, the BackgroundWorker will complete, but the WMPLib control will still be running.

  • Related