我正在使用NAudio库来处理音频文件。我想要做的是将多个音频放在一起,并从起点开始组合它们。如果我需要用数字解释一下;
A.wav
|-------------------------|
B.wav
|---------------|
我为此过程编写了以下代码,但此代码以下列方式组合了声音;
A.wav |--------------------| B.wav |--------------|
这是代码块;
public static void Concatenate(string outputFile, IEnumerable<string> sourceFiles)
{
outputFile = Path.Combine(@"C:\Users\umutg\OneDrive\Masaüstü\Muesyco\Combined\" + outputFile);
byte[] buffer = new byte[1024];
WaveFileWriter waveFileWriter = null;
try
{
foreach (string sourceFile in sourceFiles)
{
using (WaveFileReader reader = new WaveFileReader(sourceFile))
{
if (waveFileWriter == null)
{
// first time in create new Writer
waveFileWriter = new WaveFileWriter(outputFile, reader.WaveFormat);
}
else
{
if (!reader.WaveFormat.Equals(waveFileWriter.WaveFormat))
{
throw new InvalidOperationException("Can't concatenate WAV Files that don't share the same format");
}
}
int read;
while ((read = reader.Read(buffer, 0, buffer.Length)) > 0)
{
waveFileWriter.WriteData(buffer, 0, read);
}
}
}
}
finally
{
if (waveFileWriter != null)
{
waveFileWriter.Dispose();
}
}
}
修改
public static string CreateMashup(List<string> files, string filename)
{
List<AudioFileReader> mixList = new List<AudioFileReader>();
// because there is no mash up with less than 2 files
if (files.Count() < 2)
{
throw new Exception("Not enough files selected!");
}
try
{
var mixer = new WaveMixerStream32
{
AutoStop = true
};
var outputFile = Path.Combine(@"C:\Users\umutg\OneDrive\Masaüstü\Muesyco\Combined\" + filename);
foreach (var file in files)
{
var filePath = Path.Combine(@"C:\Users\umutg\OneDrive\Masaüstü\Muesyco\Download\" + file);
if (File.Exists(filePath))
{
var reader = new AudioFileReader(filePath);
mixList.Add(reader);
}
}
var _mixer = new MixingSampleProvider(mixList);
WaveFileWriter.CreateWaveFile16(outputFile, _mixer);
return outputFile;
}
catch (Exception)
{
// TODO: handle exception
throw;
}
}