目前我正在我的代码中执行此操作,
playbackElement1.AutoPlay = true;
playbackElement1.SetSource(stream, this.m_recordStorageFile.FileType);
playbackElement1.Position = new TimeSpan(0, 0, 0, 0, 5000);
playbackElement1.Play();
它不起作用,检查超过 5 秒的视频。
目前我正在我的代码中执行此操作,
playbackElement1.AutoPlay = true;
playbackElement1.SetSource(stream, this.m_recordStorageFile.FileType);
playbackElement1.Position = new TimeSpan(0, 0, 0, 0, 5000);
playbackElement1.Play();
它不起作用,检查超过 5 秒的视频。
有两个问题。首先,MediaElement只能在媒体加载后设置位置,通过处理MediaOpened事件来确定。其次,并非所有媒体都是可搜索的。通过调用CanSeek进行检查。使用类似的东西:
playbackElement1.AutoPlay = true;
// Will fire after the media has loaded
playbackElement1.MediaOpened += (source, args) =>
{
MediaElement player = (MediaElement) source;
if (player.CanSeek)
{
player.Position = new TimeSpan(0, 0, 0, 0, 5000);
}
}
playbackElement1.SetSource(stream, this.m_recordStorageFile.FileType);
加载后,使用NaturalDuration属性查看媒体的长度,如果需要,使用HasTimeSpan和TimeSpan属性将其转换为 TimeSpan。
简而言之,您需要在 MediaElement 下方添加一个 Slider,就像在任何视频播放器中一样... - Slider 将更新播放器当前位置 - Timer 将每 300 毫秒更新一次滑块与当前播放器位置
代码:
<Slider x:Name="videoSlider" Thumb.DragStarted="videoSlider_DragStarted" Thumb.DragCompleted="videoSlider_DragCompleted" Margin="10,0,10,30" Height="18" VerticalAlignment="Bottom"/>
<MediaElement x:Name="videoPlayer" Margin="4,59,152,53" Volume=".5" MediaOpened="videoPlayer_MediaOpened">
[这是带有滑块的媒体元素的图片][1]
现在我们有了一个媒体元素和一个滑块……下一步:C# 代码 :)
public partial class MainWindow : Window
{
bool isSeekingMedia = false;
DispatcherTimer seeker; // the timer to update the Slider
public MainWindow()
{
InitializeComponent();
player = new MediaPLayer();
IsPlaying(false);
seeker = new DispatcherTimer();
seeker.Interval = TimeSpan.FromMilliseconds(200);
seeker.Tick += Seeker_Tick;
}
///Seeker_Tick will update the Slider position while the video is playing
private void Seeker_Tick(object sender, EventArgs e)
{
try
{
MediatimeCounter.Content = String.Format("{0:hh}:{0:mm}:{0:ss}/{1:hh}:{1:mm}:{1:ss}", videoPlayer.Position, videoPlayer.NaturalDuration.TimeSpan);
if (!isSeekingMedia)
{
videoSlider.Value = videoPlayer.Position.TotalSeconds;
}
}
catch (Exception ex) { }
}
//This code is going to set Seeking to true to avoid playing the video if the user is changing the slider position... it kinda causes a performance issue.. so it's better to update the video position once the slider dragging event is completed.
private void videoSlider_DragStarted(object sender, RoutedEventArgs e)
{
isSeekingMedia = true;
}
//and this code is to update the video position based on the slider value.
private void videoSlider_DragCompleted(object sender, RoutedEventArgs e)
{
if (videoPlayer.Source != null)
{
isSeekingMedia = false;
this.videoPlayer = player.SeekVideo(videoPlayer, videoSlider.Value);
}
}