Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 886
Matey Avatar asked Jan 09 '23 01:01

Matey


2 Answers

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

  • first is to read it directly from file's MusicProperties by using GetMusicPropertiesAsync():
   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
like image 172
Romasz Avatar answered Jan 19 '23 01:01

Romasz


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

like image 25
CodeCaster Avatar answered Jan 19 '23 02:01

CodeCaster