apexsquirt

Microtonal keyboard generator

Nov 21st, 2017
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.85 KB | None | 0 0
  1. <?php
  2. $fundamentalTone = readline("Fundamental tone (in Hz) : ");
  3. $octaves = readline("Number of octaves : ");
  4. $tonesPerOctave = readline("Tones per octave : ");
  5. function tone_generator($freqOfTone = 440, $i) {
  6. $sampleRate = 44100;
  7. $samplesCount = 80000;
  8.  
  9. $amplitude = 0.25 * 32768;
  10. $w = 2 * pi() * $freqOfTone / $sampleRate;
  11.  
  12. $samples = array();
  13. for ($n = 0; $n < $samplesCount; $n++) {
  14.     $samples[] = (int)($amplitude *  sin($n * $w));
  15. }
  16.  
  17. $srate = 44100; //sample rate
  18. $bps = 16; //bits per sample
  19. $Bps = $bps/8; //bytes per sample
  20.  
  21. $str = call_user_func_array("pack",
  22.     array_merge(array("VVVVVvvVVvvVVv*"),
  23.         array(//header
  24.             0x46464952, //RIFF
  25.             1600038, //File size
  26.             0x45564157, //WAVE
  27.             0x20746d66, //"fmt " (chunk)
  28.             16, //chunk size
  29.             1, //compression
  30.             1, //nchannels
  31.             $srate, //sample rate
  32.             $Bps*$srate, //bytes/second
  33.             $Bps, //block align
  34.             $bps, //bits/sample
  35.             0x61746164, //"data"
  36.             160000 //chunk size
  37.         ),
  38.         $samples //data
  39.     )
  40. );
  41. $myfile = fopen("sine$i.wav", "wb") or die("Unable to open file!");
  42. fwrite($myfile, $str);
  43. fclose($myfile);
  44. }
  45. $content = "<title>SINE, that's the wrong NUMBAH !</title>
  46. <style>
  47. table {
  48. height : 100%;
  49. width  : 100%;
  50. }
  51. td {
  52. border : solid 1px black;
  53. width  : " . (100/$tonesPerOctave) . "%;
  54. }
  55. </style>
  56. <table cellspacing='0'>
  57. ";
  58. for ($t = 0; $t < $tonesPerOctave*$octaves; $t++) {
  59.  tone_generator($fundamentalTone*pow(2,$t/$tonesPerOctave), $t);
  60.  if ($t % $tonesPerOctave == 0) {
  61.   $content .= "\n<tr>";
  62.  }
  63.  $content .= "<script>var sine$t = new Audio('sine$t.wav')</script>\n<td onclick='sine$t.play()'>&approx; " . round($fundamentalTone*pow(2,$t/$tonesPerOctave), 2) . " Hz";
  64. }
  65. file_put_contents("sine.html", $content);
  66. ?>
Add Comment
Please, Sign In to add comment