Writing musical notes to a wav file

后端 未结 3 883
失恋的感觉
失恋的感觉 2020-12-02 05:13

I am interested in how to take musical notes (e.g A, B, C#, etc) or chords (multiple notes at the same time) and write them to a wav file.

From what I understand, ea

3条回答
  •  余生分开走
    2020-12-02 05:41

    You are on the right track. :)

    Audio signal

    You do not need to do a inverse FFT (you could, but you would need to find a lib for it or implement it, plus generating a signal as input to it). It is much easier to directly generate the result we expect from that IFFT, which is a sine signal with the given frequency.

    The argument to the sine depends on both the note you want generated and the sampling frequency of the wave file you generate (often equal to 44100Hz, in your example you are using 11025Hz).

    For a 1 Hz tone you need to have a sine signal with one period equal to one second. With 44100 Hz, there are 44100 sample per second, which means that we need to have a sine signal with one period equal to 44100 samples. Since the period of sine is equal to Tau (2*Pi) we get:

    sin(44100*f) = sin(tau)
    44100*f = tau
    f = tau / 44100 = 2*pi / 44100
    

    For 440 Hz we get:

    sin(44100*f) = sin(440*tau)
    44100*f = 440*tau
    f = 440 * tau / 44100 = 440 * 2 * pi / 44100
    

    In C# this would be something like this:

    double toneFreq = 440d;
    double f = toneFreq * 2d * Math.PI / 44100d;
    for (int i = 0; i

    NOTE: I have not tested this to verify the correctness of the code. I will try to do that and correct any mistakes. Update: I have updated the code to something that works. Sorry for hurting your ears ;-)

    Chords

    Chords are combination of notes (see for example Minor chord on Wikipedia). So the signal would be a combination (sum) of sines with different frequencies.

    Pure tones

    Those tones and chords will not sound natural though, because traditional instruments does not play single frequency tones. Instead, when you play an A4, there is a wide distribution of frequencies, with a concentration around 440 Hz. See for example Timbre.

提交回复
热议问题