You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.9KB

  1. var audioFileChooser = document.getElementById('audioFileChooser');
  2. audioFileChooser.addEventListener('change', readFile);
  3. function readFile() {
  4. // TODO: deal with multiple files
  5. var fileReader = new FileReader();
  6. fileReader.readAsArrayBuffer(audioFileChooser.files[0]);
  7. fileReader.addEventListener('load', function(ev) {
  8. processFile(ev.target.result);
  9. });
  10. }
  11. function processFile(file) {
  12. var context = new window.AudioContext();
  13. context.decodeAudioData(file, function(buffer) {
  14. var monoData = buffer.getChannelData(0); // start with mono, do stereo later
  15. var thisLength = monoData.length;
  16. // AudioPlayMemory requires padding to 2.9 ms boundary (128 samples @ 44100)
  17. var padLength = padding(thisLength, 128);
  18. var arraylen = ((thisLength + padLength) * 2 + 3) / 4 + 1;
  19. console.log(10241, thisLength, padLength, arraylen);
  20. console.log(monoData);
  21. });
  22. }
  23. // compute the extra padding needed
  24. function padding(sampleLength, block) {
  25. var extra = sampleLength % block;
  26. if (extra == 0) return 0;
  27. return block - extra;
  28. }
  29. function generateOutputFile(fileContents) {
  30. var textFileURL = null;
  31. var blob = new Blob([fileContents], {type: 'text/plain'});
  32. textFileURL = window.URL.createObjectURL(blob);
  33. return textFileURL;
  34. }
  35. function generateCPPFile(fileName, audioData) {
  36. var out = "";
  37. out += '// Audio data converted from audio file by wav2sketch_js\n\n';
  38. out += '#include "AudioSample' + fileName + '.h"\n\n';
  39. out += 'const unsigned int AudioSample' + fileName + '[' + audioData.length + '] = {';
  40. out += audioData.join(',') + ',};';
  41. return out;
  42. }
  43. var outputFileHolder = document.getElementById('outputFileHolder');
  44. var downloadLink = document.createElement('a');
  45. downloadLink.setAttribute('download', 'test.txt');
  46. downloadLink.href = generateOutputFile(generateCPPFile('test.wav',[0,1,2,3]));
  47. downloadLink.innerHTML = 'download link';
  48. outputFileHolder.appendChild(downloadLink);