WPF 怎么判断MediaElement视频播放完成

WPF MediaElement控件中没有属性可以直接判断视频是否被播放完了,那要怎么判断视频是否播放完成呢?

其实我们可以使用订阅MediaEnded事件,当视频播放完后,会触发该事件。

MediaElement.MediaEnded Event:在媒体结束时发生。

Namespace:

System.Windows.Controls

Assembly:

PresentationFramework.dll

下面我们来看示例:xaml中添加MediaElement控件,并赋予name值。

XML 复制代码
<Window x:Class="Software.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"        
        mc:Ignorable="d" x:Name="mainWin"  FontFamily="微软雅黑"
        WindowStartupLocation="CenterScreen" WindowStyle="None" 
        Title="MainWindow" Height="1040" Width="1920" Loaded="mainWin_Loaded">
    <Grid>       
        <MediaElement Name="myMedia" LoadedBehavior ="Manual" UnloadedBehavior="Stop" Visibility="Hidden"/>
    </Grid>
</Window>

后台实现:m_IsVoicePlayEnd :控制是否要播放下一个视频文件,在播放开始的时候,m_IsVoicePlayEnd 设置为false,等待视频播放完成后,触发MediaEnded事件,在该事件中重新对MediaEnded赋值为true。然后继续播放下一个视频。

cs 复制代码
private bool VoicePlayBack(string voicePath)
{
	try
	{
		if (!string.IsNullOrEmpty(voicePath))
		{
			if (System.IO.File.Exists(voicePath))
			{
				m_IsVoicePlayEnd = false;
				Application.Current.Dispatcher.Invoke(() =>
				{
					this.myMedia.Stop();
					this.myMedia.Source = null;
					this.myMedia.Position = new TimeSpan(0, 0, 0);
					this.myMedia.Close();
					this.myMedia.Source = new Uri(voicePath, UriKind.Relative);
					this.myMedia.ScrubbingEnabled = true;
					this.myMedia.Volume = 100;
					this.myMedia.MediaEnded += MyMedia_MediaEnded;
					this.myMedia.Play();
				});
			}
			else
				return false;
		}
		else
			return false;

		return true;
	}
	catch(Exception ex)
	{
		Console.WriteLine(ex);
		m_IsVoicePlayEnd = true;
		return false;
	}
}

//订阅MediaEnded事件
private void MyMedia_MediaEnded(object sender, RoutedEventArgs e)
{
	try
	{
		this.myMedia.MediaEnded -= MyMedia_MediaEnded;
	}
	finally
	{
		m_IsVoicePlayEnd = true;
	}
}

这里要注意个是因为多次订阅MediaEnded该事件,所以每一次视频播放完成后都要取消MediaEnded该事件的订阅,否则下次播放结束后,会多次触发MediaEnded该事件。

********************************************************************************************************************************************

相关推荐
诸葛务农1 小时前
人形机器人——电子皮肤技术路线:光学式电子皮肤及MIT基于光导纤维的分布式触觉传感电子皮肤
分布式·机器人·wpf
界面开发小八哥17 小时前
界面控件DevExpress WPF中文教程:Data Grid - 绑定数据
ui·.net·wpf·界面控件·devexpress·ui开发
界面开发小八哥1 天前
图表组件SciChart WPF再升级:v8.9带来油气井图、新交互与可视化增强
信息可视化·wpf·数据可视化·scichart
创可贴治愈心灵2 天前
WPF中UI线程频繁操作造成卡顿的处理
ui·c#·wpf
阿登林3 天前
初步学习WPF-Prism
学习·wpf
△曉風殘月〆3 天前
WPF MVVM进阶系列教程(三、使用依赖注入)
wpf·mvvm
此wei浩亦3 天前
WPF中使用 using prism.region 报错
c#·wpf·prism
dotent·4 天前
一个 WPF 文档和工具窗口布局容器
wpf
c#上位机4 天前
wpf之ComboBox
wpf
lindexi4 天前
WPF 引用 ASP.NET Core 的 AOT 版本
wpf·asp.netcore