Skip to content

Instantly share code, notes, and snippets.

@EzequielAdrianM
Created February 27, 2018 22:37
Show Gist options
  • Save EzequielAdrianM/17e60ae924888523313e05fce5c78d8b to your computer and use it in GitHub Desktop.
Save EzequielAdrianM/17e60ae924888523313e05fce5c78d8b to your computer and use it in GitHub Desktop.
WavFileUtils
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAudio.Wave;
namespace SubtitleAligner
{
public static class WavFileUtils
{
public static void TrimWavFile(string inPath, string outPath, TimeSpan cutFromStart, TimeSpan cutFromEnd)
{
using (WaveFileReader reader = new WaveFileReader(inPath))
{
using (WaveFileWriter writer = new WaveFileWriter(outPath, reader.WaveFormat))
{
double bytesPerMillisecond = reader.WaveFormat.AverageBytesPerSecond / 1000;
int startPos = (int) (cutFromStart.TotalMilliseconds * bytesPerMillisecond);
startPos = startPos - startPos % reader.WaveFormat.BlockAlign;
int endBytes = (int) (cutFromEnd.TotalMilliseconds * bytesPerMillisecond);
endBytes = endBytes - endBytes % reader.WaveFormat.BlockAlign;
int endPos = endBytes;
TrimWavFile(reader, writer, startPos, endPos);
}
}
}
private static void TrimWavFile(WaveFileReader reader, WaveFileWriter writer, int startPos, int endPos)
{
reader.Position = startPos;
byte[] buffer = new byte[reader.WaveFormat.BlockAlign * 100];
while (reader.Position < endPos)
{
int bytesRequired = (int)(endPos - reader.Position);
if (bytesRequired > 0)
{
int bytesToRead = Math.Min(bytesRequired, buffer.Length);
int bytesRead = reader.Read(buffer, 0, bytesToRead);
if (bytesRead > 0)
{
writer.WriteData(buffer, 0, bytesRead);
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment