0

我正在制作一个简单的音乐播放器,实现 WMPlib 来播放媒体文件....我正在尝试使用打开文件对话框打开文件...对话框出现并且能够选择文件但是当我尝试时出现异常将文件名分配给 Player.URL

在线

Player.URL = openFileDialog1.FileName;

错误说

你调用的对象是空的。谁能给我一个关于如何将文件名分配给 player.URL 的线索

完整代码如下......

using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {

        WMPLib.WindowsMediaPlayer Player;
        public Form1()
        {
            InitializeComponent();
        }




        private void PlayFile(String url)
        {
            Player = new WMPLib.WindowsMediaPlayer();
            Player.PlayStateChange +=
                new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(Player_PlayStateChange);
            Player.MediaError +=
                new WMPLib._WMPOCXEvents_MediaErrorEventHandler(Player_MediaError);
            Player.URL = url;
            Player.controls.play();
        }

        private void Player_PlayStateChange(int NewState)
        {
            if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsStopped)
            {
                this.Close();
            }
        }

        private void Player_MediaError(object pMediaObject)
        {
            MessageBox.Show("Cannot play media file.");
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "(mp3,wav,mp4,mov,wmv,mpg)|*.mp3;*.wav;*.mp4;*.mov;*.wmv;*.mpg|all files|*.*";
            openFileDialog1.ShowDialog(); 



        }

        private void button2_Click(object sender, EventArgs e)
        {
            PlayFile(Player.URL);
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            MessageBox.Show(openFileDialog1.FileName);
            Player.URL = openFileDialog1.FileName;
        }
    }
}
4

2 回答 2

1

尝试像这样使用 openFileDialog1:

DialogResult result = openFileDialog1.ShowDialog();

if (result == DialogResult.OK)
{
   Player.URL = openFileDialog1.FileName;
}

在 button1_Click()

于 2013-01-10T07:37:53.347 回答
1

确保在使用之前创建WMPLib.WindowsMediaPlayer的实例。现在,您似乎正在单击“打开文件”按钮并尝试将返回的文件名分配给空对象。

于 2013-01-10T08:07:26.710 回答