wav-audio-encoder.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. (function(self) {
  2. var min = Math.min,
  3. max = Math.max;
  4. var setString = function(view, offset, str) {
  5. var len = str.length;
  6. for (var i = 0; i < len; ++i)
  7. view.setUint8(offset + i, str.charCodeAt(i));
  8. };
  9. var Encoder = function(sampleRate, numChannels) {
  10. this.sampleRate = sampleRate;
  11. this.numChannels = numChannels;
  12. this.numSamples = 0;
  13. this.dataViews = [];
  14. };
  15. Encoder.prototype.encode = function(buffer) {
  16. var len = 1024;
  17. this.dataViews.push(buffer);
  18. this.numSamples += len;
  19. };
  20. Encoder.prototype.finish = function(mimeType) {
  21. var dataSize = this.numChannels * this.numSamples * 2,
  22. view = new DataView(new ArrayBuffer(44));
  23. setString(view, 0, 'RIFF');
  24. view.setUint32(4, 36 + dataSize, true);
  25. setString(view, 8, 'WAVE');
  26. setString(view, 12, 'fmt ');
  27. view.setUint32(16, 16, true);
  28. view.setUint16(20, 1, true);
  29. view.setUint16(22, this.numChannels, true);
  30. view.setUint32(24, this.sampleRate, true);
  31. view.setUint32(28, this.sampleRate * 4, true);
  32. view.setUint16(32, this.numChannels * 2, true);
  33. view.setUint16(34, 16, true);
  34. setString(view, 36, 'data');
  35. view.setUint32(40, dataSize, true);
  36. this.dataViews.unshift(view);
  37. var blob = new Blob(this.dataViews, { type: 'audio/wav' });
  38. this.cleanup();
  39. return blob;
  40. };
  41. Encoder.prototype.cancel = Encoder.prototype.cleanup = function() {
  42. delete this.dataViews;
  43. };
  44. self.WavAudioEncoder = Encoder;
  45. })(self);