[英]Why does NAudio read zeros to buffer after playing the file but not before?
The following code will successfully, load, play, edit audio samples and (almost) write to audio file. 以下代码将成功,加载,播放,编辑音频样本和(几乎)写入音频文件。 I say almost because when I comment out the "Play" code it works, but leaving it in causes the buffer read:
我说这几乎是因为当我注释掉“播放”代码时,它可以工作,但是将其保留会导致读取缓冲区:
audioFile.Read(buffer, 0, numSamples);
to result in zeros. 导致零。
Do I need to reset the audioFile somehow? 我是否需要以某种方式重设audioFile? All the examples I've found don't mention any need for this.
我发现的所有示例均未提及此需求。
using System;
using NAudio.Wave;
namespace NAudioTest
{
class TestPlayer
{
static void Main(string[] args)
{
string infileName = "c:\\temp\\pink.wav";
string outfileName = "c:\\temp\\pink_out.wav";
// load the file
var audioFile = new AudioFileReader(infileName);
// play the file
var outputDevice = new WaveOutEvent();
outputDevice.Init(audioFile);
outputDevice.Play();
//Since Play only means "start playing" and isn't blocking, we can wait in a loop until playback finishes....
while (outputDevice.PlaybackState == PlaybackState.Playing) { System.Threading.Thread.Sleep(1000); }
// edit the samples in file
int fs = audioFile.WaveFormat.SampleRate;
int numSamples = (int)audioFile.Length / sizeof(float); // length is the number of bytes - 4 bytes in a float
float[] buffer = new float[numSamples];
audioFile.Read(buffer, 0, numSamples);
float volume = 0.5f;
for (int n = 0; n < numSamples; n++) { buffer[n] *= volume; }
// write edited samples to new file
var writer = new WaveFileWriter(outfileName,audioFile.WaveFormat);
writer.WriteSamples(buffer,0,numSamples);
}
}
} }
You must call Dispose
on your writer before it is a valid WAV file. 在它是有效的WAV文件之前,您必须在您的
Dispose
上调用Dispose
。 I recommend that you put it in a using
block. 我建议您将其放在
using
块中。
using(var writer = new WaveFileWriter(outfileName,audioFile.WaveFormat))
{
writer.WriteSamples(buffer,0,numSamples);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.