Matey
Matey

Reputation: 197

How to get the duration of mp3 track?

I would like to ask how can I get length of my audio file in app.

I'm loading track like this

var installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

var resourcesFolder = await installFolder.GetFolderAsync("Resources");
var mp3FilesFolder = await resourcesFolder.GetFolderAsync("mp3Files");

var audioFile = await mp3FilesFolder.GetFileAsync("sound.mp3");
var stream = await audioFile.OpenAsync(Windows.Storage.FileAccessMode.Read);

mediaplayer.SetSource(stream, audioFile.ContentType);
mediaplayer.Play();

but I don't know how to get the duration of track?

Upvotes: 5

Views: 10623

Answers (2)

Romasz
Romasz

Reputation: 29792

There are two ways to get the duration of the track:

   var audioFile = await mp3FilesFolder.GetFileAsync("sound.mp3");
   MusicProperties properties = await audioFile.Properties.GetMusicPropertiesAsync();
   TimeSpan myTrackDuration = properties.Duration;
  • the second option is to get its NaturalDuration from MediaElement or BackgroundMediaPlayer

Upvotes: 9

CodeCaster
CodeCaster

Reputation: 151710

Assuming mediaPlayer is a MediaElement, you can get the duration using MediaElement.NaturalDuration.

Upvotes: 2

Related Questions