WPF 視訊音頻播放控件MediaElement實作進度控制,音量控制執行個體
說明:
1.Volume控制音量的大小,double類型,并且實作了屬性依賴,可以用來雙向綁定;在 0 和 1. 之間的線性層表示媒體的數量。預設值為 0.5。
2.Position 擷取或設定目前播放的位置,TimeSpan類型,沒有實作屬性依賴,不能用于雙向綁定。
3.擷取媒體檔案的時間總長度,需要在MediaOpended事件設定
需要注意的是MSDN中有對NaturalDuration的備注: 在引發 MediaOpened 事件之前,NaturalDuration 是不正确的。
是以
mePlayer.NaturalDuration.TimeSpan.TotalSeconds
不能在構造函數或者其他在MediaOpened事件前的方法中調用。
Xaml代碼
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="180*"/>
<RowDefinition Height="89*"/>
</Grid.RowDefinitions>
<MediaElement x:Name="mediaElement" LoadedBehavior="Manual"
Volume="{Binding ElementName=sliderVolume,Path=Value}"
Source="F:\MyDocument\視訊\COOLUI理念篇.mp4"
MediaOpened="mediaElement_MediaOpened"
HorizontalAlignment="Left" Height="175" Margin="7,20,0,0"
VerticalAlignment="Top" Width="275" Grid.RowSpan="2"/>
<Button x:Name="button" Content="播放" HorizontalAlignment="Left" Margin="10,31,0,0" Grid.Row="1" VerticalAlignment="Top" Width="45" RenderTransformOrigin="0.333,-0.526" Height="35" Click="button_Click"/>
<Label x:Name="label" Content="音量:" HorizontalAlignment="Left" Margin="73,50,0,0" Grid.Row="1" VerticalAlignment="Top" Height="25" Width="46"/>
<Slider x:Name="sliderVolume" Minimum="0" Maximum="1" Value="0.5"
HorizontalAlignment="Left" Margin="119,52,0,0" Grid.Row="1" VerticalAlignment="Top" Width="164" Height="18"/>
<Label x:Name="label1" Content="進度:" HorizontalAlignment="Left" Margin="73,21,0,0" Grid.Row="1" VerticalAlignment="Top" Height="25" Width="46"/>
<Slider x:Name="sliderPosition"
ValueChanged="sliderPosition_ValueChanged"
HorizontalAlignment="Left"
Margin="119,23,0,0" Grid.Row="1"
VerticalAlignment="Top" Width="164" Height="18"/>
<Label x:Name="label2"
Content="{Binding ElementName=sliderPosition,Path=Value}"
HorizontalAlignment="Left" Margin="140,6,0,0"
VerticalAlignment="Top" Height="22" Width="70" Grid.Row="1"/>
</Grid>
C#背景代碼:
如果需要界面修改Position,使用定時器控制媒體檔案的狀态
//播放按鈕
private void button_Click(object sender, RoutedEventArgs e)
{
if (button.Content.ToString() == "播放")
{
button.Content = "暫停";
mediaElement.Play();
}
else
{
button.Content = "播放";
mediaElement.Pause();
}
}
DispatcherTimer timer = null;
private void mediaElement_MediaOpened(object sender, RoutedEventArgs e)
{
sliderPosition.Maximum = mediaElement.NaturalDuration.TimeSpan.TotalSeconds;
//媒體檔案打開成功
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += new EventHandler(timer_tick);
timer.Start();
}
private void timer_tick(object sender, EventArgs e)
{
sliderPosition.Value = mediaElement.Position.TotalSeconds;
}
//控制視訊的位置
private void sliderPosition_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
//mediaElement.Stop();
mediaElement.Position = TimeSpan.FromSeconds(sliderPosition.Value);
//mediaElement.Play();
}