Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

69 lines
2.3KB

  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 OfflineAudioContext(1,10*44100,44100);
  13. context.decodeAudioData(file, function(buffer) {
  14. var monoData = buffer.getChannelData(0); // start with mono, do stereo later
  15. var outputData = [];
  16. for(var i=0;i<monoData.length;i+=2) {
  17. var a = floatToUnsignedInt16(monoData[i]);
  18. var b = floatToUnsignedInt16(monoData[i+1]);
  19. outputData.push((65536*b + a).toString(16));
  20. }
  21. var padLength = padding(outputData.length, 128);
  22. for(var i=0;i<padLength;i++) {
  23. outputData.push((0).toString(16));
  24. }
  25. console.log(outputData);
  26. });
  27. }
  28. function floatToUnsignedInt16(f) {
  29. f = Math.max(-1, Math.min(1, f));
  30. var uint;
  31. // horrible hacks going on here - basically i don't understand bitwise operators
  32. if(f>=0) uint = Math.round(f * 32767);
  33. else uint = Math.round((f + 1) * 32767 + 32768);
  34. return uint;
  35. }
  36. // compute the extra padding needed
  37. function padding(sampleLength, block) {
  38. var extra = sampleLength % block;
  39. if (extra == 0) return 0;
  40. return block - extra;
  41. }
  42. function generateOutputFile(fileContents) {
  43. var textFileURL = null;
  44. var blob = new Blob([fileContents], {type: 'text/plain'});
  45. textFileURL = window.URL.createObjectURL(blob);
  46. return textFileURL;
  47. }
  48. function generateCPPFile(fileName, audioData) {
  49. var out = "";
  50. out += '// Audio data converted from audio file by wav2sketch_js\n\n';
  51. out += '#include "AudioSample' + fileName + '.h"\n\n';
  52. out += 'const unsigned int AudioSample' + fileName + '[' + audioData.length + '] = {';
  53. out += audioData.join(',') + ',};';
  54. return out;
  55. }
  56. var outputFileHolder = document.getElementById('outputFileHolder');
  57. var downloadLink = document.createElement('a');
  58. downloadLink.setAttribute('download', 'test.txt');
  59. downloadLink.href = generateOutputFile(generateCPPFile('test.wav',[0,1,2,3]));
  60. downloadLink.innerHTML = 'download link';
  61. outputFileHolder.appendChild(downloadLink);