简体   繁体   English

如何播放媒体文件的最后x秒

[英]How to play last x seconds of media file

I need to play last 20 seconds of audio file. 我需要播放音频文件的最后20秒。 I try to specify Position property of myMediaPlayer , but there is a problem. 我尝试指定myMediaPlayer Position属性,但是存在问题。 Because I try to play LAST seconds of file I cannot set Position property of audio file like this: 因为我尝试播放文件的最后几秒钟,所以无法像这样设置音频文件的Position属性:

myMediaPlayer.Position = new TimeSpan(0, 0, 20);

I need to set Position property like this 我需要像这样设置Position属性

myMediaPlayer.Position = new TimeSpan(0, 0, DURATION_OF_FILE - 20);

Computing of audio file duration is the problem. 问题是音频文件持续时间的计算。 Firstly, I don't know duration of file, therefore I try to compute it in MediaOpened event handler. 首先,我不知道文件的持续时间,因此我尝试在MediaOpened事件处理程序中MediaOpened进行计算。

void MediaOpened(object sender, System.Windows.RoutedEventArgs e)
{
    _duration = myMediaElement.NaturalDuration.TimeSpan;
}

To invoke MediaOpened I need to start play audio file, so I am enforced to write in constructor: 要调用MediaOpened我需要开始播放音频文件,因此我被强制编写为构造函数:

// Just for MediaOpened call
myMediaElement.Play();

// I need not playing file right here, so I stop playing immediately
myMediaElement.Stop();

Now duration is computed and all seems to be good. 现在计算了持续时间,一切似乎都很好。 But after that fake play-stop operations myMediaPlayer ignores Position property! 但是,在执行这些假的停止播放操作之后, myMediaPlayer忽略Position属性! Audio file is always opened from the beginning, from the first second whatever Position is set. 无论Position设置,音频文件始终从头开始,从头开始打开。

How can it be solved? 如何解决?

XAML: XAML:

<StackPanel>
    <MediaElement  Name="myMediaElement"
                    LoadedBehavior="Manual"/>
    <Button Click="SeekToMediaPosition">Click</Button>
</StackPanel>

.cs 的.cs

TimeSpan _duration;

public MainWindow()
{
    InitializeComponent();

    myMediaElement.Source = new Uri("D:/VS_Projects/WpfApplication1/WpfApplication1/Resources/Audio.mp3");
    myMediaElement.MediaOpened += new System.Windows.RoutedEventHandler(MediaOpened);

    myMediaElement.Play();
    myMediaElement.Stop();
}

void MediaOpened(object sender, System.Windows.RoutedEventArgs e)
{
    _duration = myMediaElement.NaturalDuration.TimeSpan;
}


private void SeekToMediaPosition(object sender, RoutedEventArgs args)
{
    var test = (Int32)Math.Truncate(_duration.TotalSeconds) - 20;

    TimeSpan ts = new TimeSpan(0, 0, test);
    myMediaElement.Position = ts;
    myMediaElement.Play();
}

Add UnloadedBehavior="Manual" to the media element. 将UnloadedBehavior =“ Manual”添加到media元素。 Hope it works 希望能奏效

Instead of doing myMediaElement.Stop(); 而不是做myMediaElement.Stop(); , do myMediaElement.Pause(); ,执行myMediaElement.Pause(); .

Doing Stop() resets the player and does not allow you to set the Position . 进行Stop()重置播放器,并且不允许您设置Position Goofy, I know, but that's how it works. 高飞,我知道,但这就是它的原理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM