example.k 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. \l wav.k
  2. / Think DSP [[https://greenteapress.com/wp/think-dsp/]]
  3. / Mathematics of DFT [[https://ccrma.stanford.edu/~jos/mdft/]]
  4. / See also [[http://arlyle.sdf.org/k/sound.k]]
  5. para:`0:
  6. / sine wave: 25 samples for one cycle, 440 cycles for 11000 samples per second
  7. FR:11025 / framerate
  8. HZ:27.5 / frequency
  9. AMP:0.5 / amplitude
  10. DR:1.0 / duration
  11. WIDTH:2 / sample width in bytes
  12. rng:2/~!8*WIDTH / quantization range
  13. nt:note[12] / twelve tone system
  14. hz:8*HZ / Base note
  15. mel:{s:+/12 -12*(,'"+-")~/:\:t:(~#:)_" "\x;,/(((~^n)*+\s)+n:0 2 3 5 7 8 10"abcdefgr"?t)@&~s}
  16. chrd:{+/1(+\12*<':)\+/(+\0 2 1 2 2 1 2;-1 0 1)@'("abcdefg";"b #")?'+(" "\x)@/:\:0 1}
  17. dur:{*/(1%4(2*)\1;1.5 1)@'("whqes";". ")?'+((~#:')_" "\x)@/:\:0 1}
  18. mkpcm:{z 1:mkchnk["RIFF"]@,/("WAVE";mkfmt pcm.(x);mkchnk["data";y])}
  19. ser:{,/+|`c$(x#256)\y}
  20. ys:+/sin[;AMP;0;ph[FR;DR]]'hz*nt[chrd "c eb a"]
  21. para"Play a chord: ",wav:"test1.wav"
  22. mkpcm[(1;FR;WIDTH);ser[WIDTH]qnt[rng]apo[0.015]AMP*nrm[1-1e-15]ys;wav]
  23. para""
  24. hz*:2
  25. tune:("g g g d e c r r + c"
  26. "e q q e q e. s q e.")
  27. tone:{$[^y;&#z;apo[0.05;sin[hz*nt y+2;AMP;0]z]],&_(1-x)*(1%x)*#z}
  28. ys:,/tone[0.65].'+(mel@;ph[FR]'0.65*dur@)@'tune
  29. para"Play a tune: ",wav:"test2.wav"
  30. mkpcm[(1;FR;WIDTH);ser[WIDTH]qnt[rng]apo[0.015]AMP*nrm[1-1e-15]ys;wav]
  31. para""
  32. ys:sin[hz*nt[2];0.5*AMP;0;ph[FR;DR]]
  33. /ys+:cos[2*hz*nt[4];1.5*AMP;0;ph[FR;DR]]
  34. para"Play a note: ",wav:"test3.wav"
  35. mkpcm[(1;FR;WIDTH);ser[WIDTH]qnt[rng]apo[0.015]AMP*nrm[1-1e-15]ys;wav]
  36. para""
  37. / WARNING: Be cautious with the volume while testing!!
  38. para"Parse a wav file: -> (depth; tag; data)"
  39. para"RIFF format is a tree structure. Depth is the depth vector for that tree."
  40. 2#(dp;tg;dt):p:prs@1:wav
  41. para""
  42. para"Map tags to data"
  43. mp:!/1_p
  44. para"fmt:"
  45. mp"fmt "
  46. para"parse fmt:"
  47. prsfmt mp"fmt "
  48. para"data length"
  49. #mp"data"
  50. \d abc
  51. \l abc.k
  52. \d .
  53. mktun:{ ys:,/tone[s].'+(abc.mel[y]@;ph[FR]'(s:0.65)*0.25*/(abc.ds;abc.tpl)@\:)@\:z
  54. mkpcm[(1;FR;WIDTH);ser[WIDTH]qnt[rng]apo[0.015]AMP*nrm[1-1e-15]ys;x]}
  55. mktun["test4.wav";("c";-1)]"G/GGD/EC/>>z/zc/>z/"