如何在 UWP 中 trim mp3 文件

How can I trim mp3 file in UWP

我想在我的 UWP win 10 应用程序中 trim 一个音乐文件 (mp3)。我尝试使用 Naudio,但它在我的应用程序中不起作用,我该怎么做?

有人有什么想法吗?

如果你想trim一个mp3文件,你可以使用Windows.Media.Editing namespace, especially MediaClip class

默认情况下,此 class 用于从视频文件中剪辑。但是我们也可以通过在渲染时设置MediaEncodingProfile in MediaComposition.RenderToFileAsync方法来使用这个class到trimmp3文件。

以下是一个简单示例:

var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
openPicker.FileTypeFilter.Add(".mp3");

var pickedFile = await openPicker.PickSingleFileAsync();
if (pickedFile != null)
{
    //Created encoding profile based on the picked file
    var encodingProfile = await MediaEncodingProfile.CreateFromFileAsync(pickedFile);

    var clip = await MediaClip.CreateFromFileAsync(pickedFile);

    // Trim the front and back 25% from the clip
    clip.TrimTimeFromStart = new TimeSpan((long)(clip.OriginalDuration.Ticks * 0.25));
    clip.TrimTimeFromEnd = new TimeSpan((long)(clip.OriginalDuration.Ticks * 0.25));

    var composition = new MediaComposition();
    composition.Clips.Add(clip);

    var savePicker = new Windows.Storage.Pickers.FileSavePicker();
    savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
    savePicker.FileTypeChoices.Add("MP3 files", new List<string>() { ".mp3" });
    savePicker.SuggestedFileName = "TrimmedClip.mp3";

    StorageFile file = await savePicker.PickSaveFileAsync();
    if (file != null)
    {
        //Save to file using original encoding profile
        var result = await composition.RenderToFileAsync(file, MediaTrimmingPreference.Precise, encodingProfile);

        if (result != Windows.Media.Transcoding.TranscodeFailureReason.None)
        {
            System.Diagnostics.Debug.WriteLine("Saving was unsuccessful");
        }
        else
        {
            System.Diagnostics.Debug.WriteLine("Trimmed clip saved to file");
        }
    }
}