简体   繁体   English

如何在UWP中修剪mp3文件

[英]How can I trim mp3 file in UWP

I want to trim a music file(mp3) in my UWP win 10 app. 我想在UWP Win 10应用程序中修剪音乐文件(mp3)。 I try using Naudio but it's not working in my app, so how can i do it ? 我尝试使用Naudio,但无法在我的应用程序中使用,那么我该怎么办?

Anyone any ideas? 有任何想法吗?

If you want to trim a mp3 file, you can use Windows.Media.Editing namespace , especially MediaClip class . 如果要修剪mp3文件,则可以使用Windows.Media.Editing命名空间 ,尤其是MediaClip类

By default, this class is used for clipping from a video file. 默认情况下,此类用于从视频文件剪辑。 But we can also use this class to trim mp3 file by setting MediaEncodingProfile in MediaComposition.RenderToFileAsync method while rendering. 但是我们也可以通过在渲染时在MediaComposition.RenderToFileAsync方法中设置MediaEncodingProfile来使用此类来修剪mp3文件。

Following is a simple sample: 以下是一个简单的示例:

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");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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