波形合成まとめ

今まで作った波形合成プログラムをファンクションにしました。

fs=22050;                   // default sampling frequency of Scilab[Hz]
sec=fs;                     // unit of time
Hz=2*%pi/fs;                // unit of frequency

// generate harmonics of tone. 
// fre : 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(fre,harm,len)
  y=0
  index=[1:len]
  for i=harm 
    y=y+i(2)*sin(i(1)*fre*index) 
  end
endfunction

// generate sawtooth
// fre : frequency by scalar
// len : length of wave
function y=gen_sawtooth(fre,len)
  index=fre*[1:len]/2/%pi;
  y=(index-ceil(index)+0.5)*2;
endfunction

// generate square wave
// fre : frequency by scalar
// duty : duty cycle. 0 .. 1.0
// len : length of wave
function y=gen_square(fre,duty,len)
  saw=gen_sawtooth(fre,len)/2-0.5;
  y=max(min((ceil(saw+duty)-0.5)*2,1),-1);
endfunction

wave=gen_harmonics( 440*Hz, [1,3,5,7;1,1/3,1/5,1/7], 3*sec);
playsnd( wave );

wave=gen_sawtooth( 440*Hz, 3*sec );
playsnd(wave );

wave=gen_square( 440*Hz, 0.3, 3*sec);
playsnd(wave);