简体   繁体   中英

How to play last x seconds of media file

I need to play last 20 seconds of audio file. I try to specify Position property of myMediaPlayer , but there is a problem. Because I try to play LAST seconds of file I cannot set Position property of audio file like this:

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

I need to set Position property like this

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.

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:

// 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! Audio file is always opened from the beginning, from the first second whatever Position is set.

How can it be solved?

XAML:

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

.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. Hope it works

Instead of doing myMediaElement.Stop(); , do myMediaElement.Pause(); .

Doing Stop() resets the player and does not allow you to set the Position . Goofy, I know, but that's how it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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