如何获得mp3曲目的持续时间?

How to get the duration of mp3 track?

我想问一下如何在应用程序中获取我的音频文件的长度。

我正在像这样加载曲目

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();

但是我不知道如何获取曲目的时长?

假设 mediaPlayerMediaElement,您可以使用 MediaElement.NaturalDuration.

获取持续时间

有两种方法可以获取曲目的时长:

   var audioFile = await mp3FilesFolder.GetFileAsync("sound.mp3");
   MusicProperties properties = await audioFile.Properties.GetMusicPropertiesAsync();
   TimeSpan myTrackDuration = properties.Duration;
  • 第二个选项是从 MediaElementBackgroundMediaPlayer[=21 获取其 NaturalDuration =]