简单的MP3播放器,通知不工作

时间:2014-06-08 06:07:33

标签: c# winmm

C#beginner here。我希望在歌曲结束后让播放器立即停止,所以我尝试了解决方案stated here。问题是歌曲结束后播放器没有停止,我需要手动点击停止按钮才能选择另一首歌曲。我在某处做错了吗?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace MusicP
{
    public partial class Form1 : Form
    {
        string command = "";

        [DllImport("winmm.dll")]
        private static extern long mciSendString(string lpstrCommand, StringBuilder lpstrReturnString, int uReturnLength, int hwndCallback);

        public Form1()
        {
            InitializeComponent();
        }

        public const int MM_MCINOTIFY = 953;

        // Override the WndProc function in the form
        protected override void WndProc(ref Message m)
        {

            if (m.Msg == MM_MCINOTIFY)
            {
                Stop_Click(this, EventArgs.Empty);
            }
            base.WndProc(ref m);
        }

        private void Open_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "MP3 Files|*.mp3";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string file = ofd.FileName;
                label1.Text = ofd.SafeFileName;
                command = "open \"" + file + "\" type MPEGVideo alias MP3";
                mciSendString(command, null, 0, 0);
            }
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {

        }

        private void Play_Click(object sender, EventArgs e)
        {
            if (label1.Text == "")
            {
                Open_Click(this, EventArgs.Empty);
            }
            command = "play MP3 notify";
            mciSendString(command, null, 0, 0);
        }

        private void Stop_Click(object sender, EventArgs e)
        {
            command = "stop MP3";
            mciSendString(command, null, 0, 0);

            command = "close MP3";
            mciSendString(command, null, 0, 0);
        }

        private void Pause_Click(object sender, EventArgs e)
        {
            command = "pause MP3";
            mciSendString(command, null, 0, 0);
        }

        private void Resume_Click(object sender, EventArgs e)
        {
            command = "resume MP3";
            mciSendString(command, null, 0, 0);
        }

    }
}

非常感谢!

2 个答案:

答案 0 :(得分:0)

追加

  

通知

  

播放MediaFile

命令:

mciSendString("play MediaFile notify", null, 0, IntPtr.Zero);

答案 1 :(得分:0)

您已从mciSendString中删除了窗口的句柄:

mciSendString(command, null, 0, 0);

应该是这样的:

mciSendString(command, null, 0, (int)this.Handle);

现在调用Stop_Click。

你可以通过添加一个足够的命令来测试它:

label1.Text = "Stopped";