Skip to content

Instantly share code, notes, and snippets.

@BrainCrumbz
Forked from BrainCrumbz/Exception.log
Last active August 29, 2015 14:16
Show Gist options
  • Save BrainCrumbz/a9e46997db982ef20a9c to your computer and use it in GitHub Desktop.
Save BrainCrumbz/a9e46997db982ef20a9c to your computer and use it in GitHub Desktop.
Join WAV files into a WMA file with NAudio - COMException fixed
class JoiningWaveProvider : IWaveProvider
{
public JoiningWaveProvider(IEnumerable<MediaFoundationReader> inputFileReaders)
{
if (! inputFileReaders.Any())
{
throw new ArgumentException("At least one input file currentReader is needed");
}
WaveFormat firstFormat = inputFileReaders.First().WaveFormat;
IEnumerable<MediaFoundationReader> nonMatchingReaders =
inputFileReaders.Where(reader => !reader.WaveFormat.Equals(firstFormat));
if (nonMatchingReaders.Any())
{
throw new ArgumentException("All readers must have the same WAV format");
}
WaveFormat = firstFormat;
_inputFileReaders = inputFileReaders.ToList();
_readIndex = 0;
}
public WaveFormat WaveFormat { get; private set; }
public int Read(byte[] buffer, int offset, int count)
{
int currentOffset = offset;
int totalRead = 0;
int remaining = count;
for (int i = _readIndex; i < _inputFileReaders.Count && remaining > 0; i++, _readIndex++)
{
MediaFoundationReader currentReader = _inputFileReaders[i];
int readNow = currentReader.Read(buffer, currentOffset, remaining);
currentOffset += readNow;
totalRead += readNow;
remaining -= readNow;
}
return totalRead;
}
private int _readIndex;
private readonly List<MediaFoundationReader> _inputFileReaders;
}
// ...
/* Mixing WaveFileReader with MediaFoundationEncoder causes an exception.
* Stick with MediaFoundationReader when working with MediaFoundation namespace.
List<WaveFileReader> waveFileReaders = BuildTheReaderListFromPathNames();
*/
List<MediaFoundationReader> waveFileReaders = BuildTheReaderListFromPathNames();
IWaveProvider joinedWaveProvider = buildProvider(waveFileReaders);
// This one causes Exception
MediaFoundationEncoder.EncodeToWma(joinedWaveProvider, _joinedOutputFile, 48000);
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment