我将两个mp3文件混合成一个问题。实际上,我已经找到了一些使用NAudio库的测试代码,但对我来说这太慢了。我是“音频编程”的新手,所以我需要你的帮助,建议如何使算法更快地解决这个问题。
代码在8 +秒内将两个文件混合成一个,这太慢了。实际上,我检查过并且ConvertWavToMp3()持续8秒。文件1.mp3和2.mp3长度超过3分钟。
static void Main(string[] args)
{
var watch = Stopwatch.StartNew();
watch.Start();
var path = @"C:\Users\gutek\Desktop\";
// read mp3 files from disk
Mp3FileReader mpbacground = new Mp3FileReader(path + "1.mp3");
Mp3FileReader mpMessage = new Mp3FileReader(path + "2.mp3");
//convert them into wave stream or decode the mp3 file
WaveStream background = WaveFormatConversionStream.CreatePcmStream(mpbacground);
WaveStream message = WaveFormatConversionStream.CreatePcmStream(mpMessage);
var mixer = new WaveMixerStream32();
mixer.AutoStop = true;
var messageOffset = background.TotalTime;
var messageOffsetted = new WaveOffsetStream(
message, TimeSpan.FromSeconds(10), TimeSpan.Zero, message.TotalTime.Subtract(TimeSpan.FromSeconds(30)));
var background32 = new WaveChannel32(background);
background32.PadWithZeroes = false;
// set the volume of background file
background32.Volume = 0.4f;
//add stream into the mixer
mixer.AddInputStream(background32);
var message32 = new WaveChannel32(messageOffsetted);
message32.PadWithZeroes = false;
// set the volume of 2nd mp3 song
message32.Volume = 0.6f;
mixer.AddInputStream(message32);
var wave32 = new Wave32To16Stream(mixer);
//encode the wave stream into mp3
var mp3Stream = ConvertWavToMp3(wave32);
// write mp3 on the disk
File.WriteAllBytes(path + "output.mp3", mp3Stream.ToArray());
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
Console.ReadKey();
}
public static MemoryStream ConvertWavToMp3(Wave32To16Stream wavFile)
{
using (var retMs = new MemoryStream())
using (var wtr = new LameMP3FileWriter(retMs, wavFile.WaveFormat, 128))
{
wavFile.CopyTo(wtr);
return retMs;
}
}