高調波も生成する(2)

昨日のエントリでは高調波を作り出すために正弦波を直接加算していました。正しいやり方なのですが、5つくらいの正弦波の足し算になってくると手に負えなくなります。少なくとも可読性は最悪。そこで、関数を作ってみます。
gen_harmonics()関数は、基本波の周波数、高調波とその振幅、波形の長さ(秒)を受け取って信号
を生成します。

fs=22050;                   // default sampling frequency of Scilab[Hz]
sec=fs;                     // unit of time
Hz=2*%pi/fs;                // unit of frequency
// generate harmonics of tone. 
// freq : base harmonic frequency by scalar
// harm : harmonics matrix 2xN where N is number of harmonics. 
//        1st raw is the multiplier of freq. 2nd raw is the amplitude coeff
//        example : [ 1,3,5,7,... ; 1,1/3,1/5,1/7...] makes square wave.
// len : length of wave
function y=gen_harmonics(freq,harm,len)
  y=0
  index=[1:len]
  for i=harm 
    y=y+i(2)*sin(i(1)*freq*index) 
  end
endfunction

                            // generate 440Hz wave as 3 seconds
wave=gen_harmonics( 440*Hz, [1,3,5,7;1,1/3,1/5,1/7], 3*sec);
playsnd(wave/2);            // play by 22.05kHz sampling

サンプルは440Hzを基本波として振幅を次のように与えています。

基本波 3倍高調波 5倍高調波 7倍高調波
1 1/3 1/5 1/7

関数にしたことで倍音の指定が少しだけ楽になっています。


RJBさんに対抗して私も波形合成をやってみました。440Hzの25次高調波まで加算した擬似矩形波に、440Hzの正弦波を重畳しています。