c# - 播放未知时间的正弦波

标签 c# audio wave trigonometry

一整天我都在寻找一些教程或一段代码,“只是”在“无限”时间内播放简单的正弦波。我知道这听起来有点疯狂。

但我希望能够及时改变音调的频率,例如 - 增加它。 想象一下,我想播放音调 A,并以每 3 毫秒的“+5”频率步长将其增加到 C(这实际上只是示例),不想有空闲的地方,停止音调。

这可能吗?或者你能帮帮我吗?

最佳答案

使用 NAudio 库进行音频输出。

做笔记 wave 提供者:

class NotesWaveProvider : WaveProvider32
{
    public NotesWaveProvider(Queue<Note> notes)
    {
        this.Notes = notes;
    }
    public readonly Queue<Note> Notes;
    int sample = 0;

    Note NextNote()
    {
        for (; ; )
        {
            if (Notes.Count == 0)
                return null;
            var note = Notes.Peek();
            if (sample < note.Duration.TotalSeconds * WaveFormat.SampleRate)
                return note;

            Notes.Dequeue();
            sample = 0;
        }

    }
    public override int Read(float[] buffer, int offset, int sampleCount)
    {
        int sampleRate = WaveFormat.SampleRate;
        for (int n = 0; n < sampleCount; n++)
        {
            var note = NextNote();
            if (note == null)
                buffer[n + offset] = 0;
            else
                buffer[n + offset] = (float)(note.Amplitude * Math.Sin((2 * Math.PI * sample * note.Frequency) / sampleRate));
            sample++;
        }
        return sampleCount;
    }
}
class Note
{
    public float Frequency;
    public float Amplitude = 1.0f;
    public TimeSpan Duration = TimeSpan.FromMilliseconds(50);

}

开始播放:

WaveOut waveOut;
this.Notes = new Queue<Note>(new[] { new Note { Frequency = 1000 }, new Note { Frequency = 1100 } });
var waveProvider = new NotesWaveProvider(Notes);
waveProvider.SetWaveFormat(16000, 1); // 16kHz mono    

waveOut = new WaveOut();
waveOut.Init(waveProvider);
waveOut.Play();

添加新笔记:

void Timer_Tick(...)
{
 if (Notes.Count < 10)
   Notes.Add(new Note{Frecuency = 900});
}

ps 此代码仅供引用。真正使用添加 mt-locking 等

关于c# - 播放未知时间的正弦波,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9594665/

相关文章:

c# - 如何让.NET应用程序通过代理访问互联网

c# - Pinvoke Bool - MarshalDirectiveExeption

python - 将数据附加到波形声音文件而不加载其当前内容

javascript - 使用 renderBuffer 作为 HTML5 音频标签

javascript - 停止父级 iframe 内的所有音频

windows - 您可以在 Windows wave 音频输入中重复使用缓冲区吗?

C++ - 播放正弦波产生的音调

c# - 任何人都可以知道该怎么做(错误CS1525 : Unexpected symbol)

C#抽象类说明

c# - 如何在所有音频设备上播放声音