WMPLib 音乐播放但当我切换标签时它停止

WMPLib Music plays but when I switch tabs it stops

我有食品卡车的 C# 应用程序。当顾客查看菜单时,我会播放一些音乐。在菜单表单上,我有四个选项卡。我在表单加载中有 WMPLib 代码。当表单加载时,音乐开始播放,但是当我切换到不同的选项卡时,音乐停止。我已经调试了,但是没有什么可以真正看到的,因为它运行了这些行,但在您切换选项卡时就停止了。关于在主窗体上切换选项卡时如何保持音乐播放的任何想法。我希望它能连续播放,而不仅仅是在每个选项卡上重新开始。谢谢。这是带有选项卡的表单图像。

这是表单加载代码:

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);
}

要使用 WMPLib 在后台播放 MP3,请尝试以下操作:

创建一个class(名称: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();

        }
    }
}

在表单(例如:Form1)代码中,创建上面class的一个实例:

 private HelperMp3 _helperMp3 = new HelperMp3();

然后创建一个启动音乐的方法:

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

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

订阅表单的 Load 事件(例如:Form1_Load)并添加以下代码:

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

订阅表单的 FormClosed 事件(例如:Form1_FormClosed)并添加以下代码:

Form1_FormClosed

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

或者,可以使用 BackgroundWorker。如果使用 BackgroundWorker,在 HelperMp3.cs 中将方法 PlayMp3 更改为以下内容:

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();

}

注意:如果使用BackgroundWorkerBackgroundWorker会完成,但WMPLib控件仍然是运行 .