两个MediaElement之间的延迟

时间:2016-01-26 17:12:03

标签: c# wpf

myForm上有两个媒体元素。我上传了相同的视频,但在MediaElement1和MediaElement2之间延迟了大约一秒钟。

MediaElement1.Source = new Uri("D:\\test.avi", UriKind.Relative);
MediaElement2.Source = new Uri("D:\\test.avi", UriKind.Relative);
MediaElement1.Position = TimeSpan.Zero;
MediaElement2.Position = TimeSpan.Zero;
MediaElement1.LoadedBehavior = MediaState.Play;
MediaElement2.LoadedBehavior = MediaState.Play;

XAML

<MediaElement x:Name="MediaElement1" Margin="0,0,5,126" />  
<MediaElement x:Name="MediaElement2" Margin="0,0,15,126"/>

为什么会有延迟以及如何到处走走?

1 个答案:

答案 0 :(得分:0)

以下代码可以毫不拖延地工作,必须添加一个停止命令。

        private static OpenFileDialog OpenFile()
        {
            OpenFileDialog ofd;
            ofd = new OpenFileDialog();
            ofd.AddExtension = true;
            ofd.DefaultExt = "*.*";
            ofd.Filter = "media (*.*)|*.*";
            ofd.ShowDialog();
            return ofd;
        }

        private void loadm1_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = OpenFile();
            M1.Source = new Uri(ofd.FileName, UriKind.Relative);
            M1.Position = TimeSpan.Zero;
            M1.LoadedBehavior = MediaState.Stop;
        }

        private void loadm2_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = OpenFile();
            M2.Source = new Uri(ofd.FileName, UriKind.Relative);
            M2.LoadedBehavior = MediaState.Stop;
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            M1.LoadedBehavior = MediaState.Play;
            M2.LoadedBehavior = MediaState.Play;
        }

        private void btnPause_Click(object sender, RoutedEventArgs e)
        {
            M1.LoadedBehavior = MediaState.Pause;
            M2.LoadedBehavior = MediaState.Pause;
        }

XAML

 <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="252*"/>
            <ColumnDefinition Width="265*"/>
        </Grid.ColumnDefinitions>
        <MediaElement x:Name="M1" Margin="0,0,5,126" />
        <MediaElement x:Name="M2" Grid.Column="1" Margin="0,0,15,126"/>
        <Button x:Name="loadm1" Content="Load" HorizontalAlignment="Left" Margin="10,0,0,99" Width="75" Height="22" VerticalAlignment="Bottom" Click="loadm1_Click"/>
        <Button x:Name="loadm2" Content="Load" Grid.Column="1" HorizontalAlignment="Left" Margin="10,0,0,99" Width="75" Height="22" VerticalAlignment="Bottom" Click="loadm2_Click"/>
        <Button x:Name="btnStart" Content="Start" Margin="10,0,20,20" Grid.ColumnSpan="2" Height="22" VerticalAlignment="Bottom" Click="btnStart_Click"/>
        <Button x:Name="btnPause" Content="Pause" HorizontalAlignment="Left" Margin="10,289,0,0" VerticalAlignment="Top" Width="75" Click="btnPause_Click"/>

    </Grid>