naudio / NAudio

Audio and MIDI library for .NET
MIT License
5.38k stars 1.09k forks source link

Differences at the beginning and end after a conversion WAV to MP3 #1052

Open bsuschi opened 11 months ago

bsuschi commented 11 months ago

Hello, the content after converting a WAV file to an MP3 file is not the same. I know that MP3 is a lossy format. However, when converting the MP3, something like a silence of 0.025 seconds is added at the beginning and at the end. This is clearly visible when viewed in an audio editor. I want to use MP3 files with a large bitrate to keep the file sizes down and get better results than zipping.

With my samples it is extremely important that no content is added. They are strung together and currently there is a little dropout in the playback. How can I prevent this? Or is there a better way to compress the file size? With this solution I can reduce the file sizes to 1/5 of the original.

using (var reader = new WaveFileReader(file.FullName)) { MediaFoundationEncoder.EncodeToMp3(reader, mp3FilePath, 320000); }

Many thanks in advance.

markheath commented 11 months ago

MP3 is encoded as a series of "frames" and is not sample accurate. I believe that there are other formats (maybe AAC or Opus) that can encode an exact number of samples, but MP3 is not a suitable choice for this requirement

bsuschi commented 11 months ago

Hello Mark,

thank you for your quick reply. I was not aware of this before, thank you for your good explanation. In the meantime, I have already checked a conversion to WMV and AAC. It produces pretty much the same results. Accordingly, it is not usable for my requirements. In my further considerations, I ended up with the lossless FLAC format. Is there a way to use this with NAUDIO? Is there already a possibility for encoding and decoding?

Many thanks in advance.

markheath commented 11 months ago

Newer versions of Windows come with FLAC support so MediaFoundationReader should be able to play FLAC files, and the MediaFoundationEncoder also ought to be able to encode to FLAC.

bsuschi commented 10 months ago

Hello Mark, thanks for your reply.

What am I doing wrong? I always get an error message when encoding:

System.Runtime.InteropServices.COMException: "The data specified for the media type is invalid, inconsistent or is not supported by this object. (0xC00D36B4)"

I don't get it. MediaType is not null and so it should be available after all. Can you help me here or do you have more information for me?

public static readonly Guid MFAudioFormat_FLAC = new Guid("0000F1AC-0000-0010-8000-00AA00389B71"); ... using (var reader = new WaveFileReader("Demo.wav")) { MediaType mediaType = MediaFoundationEncoder.SelectMediaType(MFAudioFormat_FLAC, new WaveFormat(44100, 2), 320000); using (var mediaFoundationEncoder = new MediaFoundationEncoder(mediaType)) { mediaFoundationEncoder.Encode("Demo.flac", reader); } }

Many thanks in advance.