以下代码将成功加载、播放、编辑音频样本并(几乎)写入音频文件。我说几乎是因为当我注释掉“播放”代码时它可以工作,但是将它留在里面会导致缓冲区读取:
audioFile.Read(buffer, 0, numSamples);
导致零。
我需要以某种方式重置音频文件吗?我发现的所有示例都没有提到对此的任何需求。
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);
}
}
}