使用的代码:
public WaveIn waveSource = null;
public WaveFileWriter waveFile = null;
public List<byte> soundBytesList = new List<byte>();
private void waveSource_DataAvailable(object sender, WaveInEventArgs e)
{
if (waveFile != null)
for (int i = 0; i < e.BytesRecorded; ++i)
soundBytesList.Add(e.Buffer[i]);
waveFile.Write(e.Buffer, 0, e.BytesRecorded);
waveFile.Flush();
}
public void waveSource_RecordingStopped(object sender, StoppedEventArgs e)
{
if (waveSource != null)
{
waveSource.Dispose();
waveSource = null;
}
if (waveFile != null)
{
waveFile.Dispose();
waveFile = null;
}
}
private void RecordButton_MouseDown(object sender, EventArgs e)
{
waveSource = new WaveIn();
waveSource.WaveFormat = new WaveFormat(44100, 1);
waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
waveSource.RecordingStopped += new EventHandler<StoppedEventArgs>(waveSource_RecordingStopped);
waveFile = new WaveFileWriter("test.wav", waveSource.WaveFormat);
waveSource.StartRecording();
}
private void RecordButton_MouseUp(object sender, EventArgs e)
{
waveSource.StopRecording();
byte[] soundBytesArrayWAV = soundBytesList.ToArray();
byte[] outB = ConvertWavToMp3(soundBytesArrayWAV );
File.WriteAllBytes("test.mp3", outB);
}
public byte[] ConvertWavToMp3(byte[] wavFile)
{
using (var retMs = new MemoryStream())
using (var ms = new MemoryStream(wavFile))
using (var rdr = new WaveFileReader(ms))
using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, 128))
{
rdr.CopyTo(wtr);
wtr.Flush();
return retMs.ToArray();
}
}
问题是我在ConvertWavToMp3方法上遇到错误,但说提供的字节数组(soundBytesArrayWAV
)没有RIFF(特定于波形的标头)。我的猜测是,我没有正确地使用soundBytesList
中的所有字节,因为如果我将所有字节加载到内存中(从写入wav的磁盘中),转换将正常进行。
你能帮我个忙吗?
答案 0 :(得分:1)
根据@Jon Skeet的建议更新的功能代码如下:
public WaveIn waveSource = null;
public WaveFileWriter waveFile = null;
public MemoryStream memStream = null;
private void waveSource_DataAvailable(object sender, WaveInEventArgs e)
{
if (waveFile != null)
{
waveFile.Write(e.Buffer, 0, e.BytesRecorded);
waveFile.Flush();
}
}
public void waveSource_RecordingStopped(object sender, StoppedEventArgs e)
{
if (waveSource != null)
{
waveSource.Dispose();
waveSource = null;
}
if (waveFile != null)
{
waveFile.Dispose();
waveFile = null;
}
}
private void RecordButton_MouseDown(object sender, EventArgs e)
{
waveSource = new WaveIn();
waveSource.WaveFormat = new WaveFormat(44100, 1);
waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
waveSource.RecordingStopped += new EventHandler<StoppedEventArgs>(waveSource_RecordingStopped);
memStream = new MemoryStream();
waveFile = new WaveFileWriter(memStream, waveSource.WaveFormat);
waveSource.StartRecording();
}
private void RecordButton_MouseUp(object sender, EventArgs e)
{
waveSource.StopRecording();
byte[] outB = memStream.ToArray();
File.WriteAllBytes("test.mp3", outB);
}