Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
音乐在C#Windows窗体应用程序中突然停止播放_C#_.net_Winforms_Media - Fatal编程技术网

音乐在C#Windows窗体应用程序中突然停止播放

音乐在C#Windows窗体应用程序中突然停止播放,c#,.net,winforms,media,C#,.net,Winforms,Media,在我的应用程序中,通常应该有两个重叠的声音(一首歌和一些简短的声音)。它工作良好,直到不时的歌曲突然停止播放。你知道我怎样才能解决这个问题吗? 以下是我用于添加歌曲和声音的函数: private void music() { var p1=new System.Windows.Media.MediaPlayer(); p1.打开(new System.Uri(@“J:\penal\penal\penal\bin\Debug\Avicii-The Nights(歌词HD.wav)); p1.玩耍(

在我的应用程序中,通常应该有两个重叠的声音(一首歌和一些简短的声音)。它工作良好,直到不时的歌曲突然停止播放。你知道我怎样才能解决这个问题吗? 以下是我用于添加歌曲和声音的函数:

private void music()
{
var p1=new System.Windows.Media.MediaPlayer();
p1.打开(new System.Uri(@“J:\penal\penal\penal\bin\Debug\Avicii-The Nights(歌词HD.wav));
p1.玩耍();
}
二等兵
{
系统.线程.线程.睡眠(500);
var p2=new System.Windows.Media.MediaPlayer();
p2.打开(new System.Uri(@“J:\penal\penal\penal\bin\Debug\happy.wav”);
p2.玩耍();
}
私人空间
{
系统.线程.线程.睡眠(500);
var p2=new System.Windows.Media.MediaPlayer();
p2.打开(new System.Uri(@“J:\penal\penal\penal\bin\Debug\sad.wav”);
p2.玩耍();
}

如果不将对
MediaPlayer
s的引用存储为字段,而仅将其存储在局部变量中,则很可能会对其进行gargabe收集。这可能会发生延迟,因为
MediaPlayer
使用的非托管资源在释放前需要
Dispose
。要解决问题,请考虑在字段中存储对<代码>媒体播放器< /代码>的引用。

private System.Windows.Media.MediaPlayer _music;
private System.Windows.Media.MediaPlayer _happy;
private System.Windows.Media.MediaPlayer _sad;
然后调整方法以使用该字段

private void musical()
{
    _music = new System.Windows.Media.MediaPlayer();
    _music.Open(new System.Uri(@"J:\penalty\penalty\penalty\bin\Debug\Avicii - The Nights (Lyrics HD).wav"));
    _music.Play();     
}
如果要重复音频(效果不太好),可以订阅
MediaEnded
事件,以便将位置设置回开始位置并重新开始播放