Advertisement
Guest User

Untitled

a guest
May 24th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. open Containers;
  2. type destination;
  3.  
  4. type pitch = C | Cs | D | Eb | E | F | Fs | G | Gs | A | Bb | B;
  5. module Pitches = Map.Make({ type t = pitch; let compare = compare; });
  6.  
  7. let pitches = Pitches.fromList
  8. [
  9. (C, 16.35),
  10. (Cs, 17.32),
  11. (D, 18.35),
  12. (Eb, 19.45),
  13. (E, 20.60),
  14. (F, 21.83),
  15. (Fs, 23.12),
  16. (G, 24.50),
  17. (Gs, 25.96),
  18. (A, 27.50),
  19. (Bb, 29.14),
  20. (B, 30.87),
  21. ];
  22.  
  23. let rec pow b e => {
  24. e == 0.0 ? 1.0 : b *. pow b (e -. 1.0);
  25. };
  26.  
  27. let getPitch pitch octave => {
  28. (pow 2.0 octave) *. Pitches.find pitch pitches;
  29. };
  30.  
  31. type oscillator = Js.t {
  32. .
  33. frequency: Js.t {
  34. .
  35. value [@bs.set] [@bs.get]: float
  36. },
  37. connect [@bs.meth] : destination => unit,
  38. _type [@bs.set] [@bs.get] : string,
  39. start [@bs.meth] : float => unit,
  40. stop [@bs.meth] : float => unit
  41. };
  42.  
  43. type audioContext = Js.t {
  44. .
  45. destination: destination,
  46. createOscillator [@bs.meth] : unit => oscillator
  47. };
  48.  
  49. external audioContext : unit => audioContext = "window.AudioContext" [@@bs.new];
  50. external createOscillator : audioContext => unit => oscillator = "" [@@bs.send];
  51.  
  52. let c = audioContext ();
  53.  
  54. let play note => {
  55. let o = c##createOscillator ();
  56. o##_type #= "square";
  57. o##frequency##value #= (getPitch note 4.0);
  58. o##connect (c##destination);
  59. o##start (0.25);
  60. o;
  61. };
  62.  
  63. let o = play B;
  64.  
  65. Js_global.setTimeout (fun _ => {o##frequency##value #= (getPitch C 4.0)}) 1000;
  66.  
  67. Js_global.setTimeout (fun _ => {o##stop 0.0}) 10000;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement