音乐突然停止在应用中播放

时间:2013-06-04 16:22:36

标签: c# wpf windows-media-player

我有这段代码:

private void OtworzPlikButton_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.ShowDialog();
        string directory = ofd.FileName;
        WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
        wplayer.URL = directory;
        wplayer.controls.play(); 
    }

我从OpenFileDialog获取文件目录,我正在使用wplayer开始播放音乐。起初它工作正常但是在20-30秒后,音乐突然停止播放,我无法弄清楚原因。我正在播放MP3文件。

1 个答案:

答案 0 :(得分:6)

您应该在类级别范围内创建WindowsMediaPlayer的实例(不在OtworzPlikButton_Click事件处理程序范围内)。

WMPLib.WindowsMediaPlayer wplayer;

private void OtworzPlikButton_Click(object sender, RoutedEventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.ShowDialog();
    string directory = ofd.FileName;
    wplayer = new WMPLib.WindowsMediaPlayer();
    wplayer.URL = directory;
    wplayer.controls.play(); 
}