我正在制作一个简单的音乐播放器,实现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;
}
}
}
答案 0 :(得分:1)
尝试像这样使用openFileDialog1:
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
Player.URL = openFileDialog1.FileName;
}
在button1_Click()
中答案 1 :(得分:1)
确保在使用之前创建 WMPLib.WindowsMediaPlayer 的实例。现在,您似乎正在单击“打开文件”按钮并尝试将返回的文件名分配给空对象。