naudio / NAudio

Audio and MIDI library for .NET
MIT License
5.57k stars 1.1k forks source link

issue with MediaFoundationEncoder.EncodeToMp3 #876

Open billsheh opened 2 years ago

billsheh commented 2 years ago

I am using MediaFoundationEncoder.EncodeToMp3 to convert a wave file to a Mp3 file, mp3 file was generated successfully, but it is not able to play back.

I also tried NAudio.Lame with success, mp3 file size was doubled and mp3 file was able to play back. Anyone can help?

MediaFoundationApi.Startup(); using (var reader = new WaveFileReader(sourceFile)) { MediaFoundationEncoder.EncodeToMp3(reader, desFile); }

========================Lame================ using (WaveFileReader wavReader = new WaveFileReader(f)) using (WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(wavReader)) using (LameMP3FileWriter fileWriter = new LameMP3FileWriter(targetFile, pcm.WaveFormat, LAMEPreset.VBR_90)) { pcm.CopyTo(fileWriter); }

domshyra commented 2 years ago

I am having an encoding as mp3 as well. Trying to trim as a wav then convert back to mp3

controller `[HttpPost(Name = "SliceMp3")] public async Task Post(IFormFile file) {

        var filePath = Path.GetTempFileName();
        var fileOutPath = Path.GetTempFileName();

        using (var stream = System.IO.File.Create(filePath))
        {
            // The formFile is the method parameter which type is IFormFile
            // Saves the files to the local file system using a file name generated by the app.
            await file.CopyToAsync(stream);

        }

        WavFileUtils.TrimWavMp3(filePath, fileOutPath, new TimeSpan(1), new TimeSpan(2));

        var memoryStream = new MemoryStream();
        using (var stream = System.IO.File.OpenRead(fileOutPath))
        {
            await stream.CopyToAsync(memoryStream);
        }

        return File(memoryStream, "audio/mp3", "myfile.mp3");
    }
    `

    `public static void TrimWavMp3(string path, string outPath, TimeSpan cutFromStart, TimeSpan cutFromEnd)
    {
        var wavFilePath = Path.GetTempFileName();
        var trimmedFilePath = Path.GetTempFileName();

        //Convert to wav
        using var readerMp3ToWav = new MediaFoundationReader(path);
        WaveFileWriter.CreateWaveFile(wavFilePath, readerMp3ToWav);

        //Trim
        TrimWavFile(wavFilePath, trimmedFilePath, cutFromStart, cutFromEnd);

        //Convert back
        using var readerWavToMp3 = new WaveFileReader(trimmedFilePath);
        MediaFoundationEncoder.EncodeToMp3(readerWavToMp3, outPath);

    }`

I get back System.ArgumentException: Was not able to create a sink writer for this file extension

using this code from TrimWavFile

if there is a way to do this trim with flip flopping the file type that would work for me too :)