Search code examples
c#audioffmpegwavnaudio

c# - WAV file trimming and adding silence


I have two recordings of same event, different lengths, started at different times. I want to synchronize them, time offset is known. I want to achieve the following:

  1. Align second one in time by the time offset.
  2. Trim second one to match the length of the first one
  3. When there is nothing to trim, add silence to match the length of the first one.

    I found the way to trim the audio, but I couldn't find solution for adding silence. Is there any way to do this with NAudio, ffmpeg or Aurio?

Solution

  • Here is a way to write silence by millisecond using NAudio:

    public static void WriteSilence(WaveFormat waveFormat, 
       int silenceMilliSecondLength, WaveFileWriter waveFileWriter)
    {
        int bytesPerMillisecond = waveFormat.AverageBytesPerSecond / 1000;
        //an new all zero byte array will play silence
        var silentBytes = new byte[silenceMilliSecondLength * bytesPerMillisecond];
        waveFileWriter.Write(silentBytes, 0, silentBytes.Length);
        waveFileWriter.Dispose();
    }