Javascript - WAV文件数据到字节数组转换问题 - 获得大量噪音

时间:2017-10-13 20:11:48

标签: javascript arrays audio wav

我有一个返回WAV文件的API。在我的Javascript中,我试图将原始数据转换为字节数组。我在最后的音频中得到了很多噪音/静电。 有人可以告诉我如何修复字节数组转换(getByteArray方法)。谢谢!

		var fileElem = document.getElementById('file-input');
		fileElem.addEventListener('change', readSingleFile, false);

		function readSingleFile(e) {
		  var file = e.target.files[0];
		  if (!file) {
		    return;
		  }
		  var reader = new FileReader();
		  reader.onload = function(e) {
		    var contents = e.target.result;
		    playAudio(contents);
		  };
		  reader.readAsText(file);
		}

		function playAudio(dataStr) {
		  var array = getByteArray(dataStr);
		  var isWAV = array[0] === 82 && array[1] === 73 && array[2] === 70 && array[3] === 70 &&
		    array[8] === 87 && array[9] === 65 && array[10] === 86 && array[11] === 69;
		  console.log("Is a valid WAV File? : " + isWAV);
		  var message = document.getElementById('message');
		  if (isWAV) {
		    message.innerHTML = "";
		    // Create blob from Uint8Array & Object URL.
		    var blob = new Blob([array], {
		      type: 'audio/wav'
		    });
		    var url = URL.createObjectURL(blob);

		    // Get DOM elements.
		    var audio = document.getElementById('audio');
		    var source = document.getElementById('source');

		    // Insert blob object URL into audio element & play.
		    source.src = url;
		    audio.load();
		    audio.play();
		  } else {
		    message.innerHTML = "You selected a non WAV file!!!";
		  }
		}

		function getByteArray(dataStr) {
		  var array = new Uint8Array(dataStr.length);
		  for (var i = 0; i < dataStr.length; i++) {
		    array[i] = dataStr.charCodeAt(i);
		  }
		  return array;
		}
<h4>Select an WAV File</h4>
<h4><span id="message" style="color: red"></span></h4>
<input type="file" id="file-input" />
<hr/>
<audio controls="controls" id="audio">
  Your browser does not support the &lt;audio&gt; tag.
  <source id="source" src="" type="audio/wav" />
</audio>

0 个答案:

没有答案