NAudio SineWave

时间:2013-03-15 02:57:03

标签: naudio

在博客上使用示例我输出了一个正弦波:

public class SineWaveProvider32 : WaveProvider32{

    int sample;

    public SineWaveProvider32()
    {
        Frequency = 1000;
        Amplitude = 0.25f; // let's not hurt our ears            
    }

    public float Frequency { get; set; }
    public float Amplitude { get; set; }

    public override int Read(float[] buffer, int offset, int sampleCount)
    {
        int sampleRate = WaveFormat.SampleRate;
        for (int n = 0; n < sampleCount; n++)
        {
            buffer[n+offset] = (float)(Amplitude * Math.Sin((2 * Math.PI * sample * Frequency) / sampleRate));
            sample++;
            if (sample >= sampleRate) sample = 0;
        }
        return sampleCount;
    }
}

当我播放这个正弦波时,它是一个无限循环。想知道我将如何输出给定长度的声音?

1 个答案:

答案 0 :(得分:2)

只要Read不返回0,正弦波就会继续播放.Read返回写入缓冲区的样本数(只要你还没有完成,就应该始终和sampleCount一样)。因此,请保留已返回的样本总数。一旦该数字等于采样率,您就播放了一秒的音频。