我使用此代码从字节生成音频元素,它创建一个简单的 wav 声音,我可以在 google chrome 或 DESKTOP 的 firefox 中播放它,但是当我想在 Google Chrome Mobile 中播放它时,它什么也不播放,在哪里是问题所在,我可以轻松播放 wav 文件,但无法在 google chrome mobile 中播放二进制数据中的音乐:
<!DOCTYPE html>
<html>
<head>
<title>Explosion Generator</title>
<script type = "text/javascript" src="../../js/jquery-1.8.3.js" ></script>
<script>
function encodeAudio16bit(data, sampleRate) {
var n = data.length;
var integer = 0, i;
// 16-bit mono WAVE header template
var header = "RIFF<##>WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00<##><##>\x02\x00\x10\x00data<##>";
// Helper to insert a 32-bit little endian int.
function insertLong(value) {
var bytes = "";
for (i = 0; i < 4; ++i) {
bytes += String.fromCharCode(value % 256);
value = Math.floor(value / 256);
}
header = header.replace('<##>', bytes);
}
// ChunkSize
insertLong(36 + n * 2);
// SampleRate
insertLong(sampleRate);
// ByteRate
insertLong(sampleRate * 2);
// Subchunk2Size
insertLong(n * 2);
// Output sound data
for (var i = 0; i < n; ++i) {
var sample = Math.round(Math.min(1, Math.max(-1, data[i])) * 32767);
if (sample < 0) {
sample += 65536; // 2's complement signed
}
header += String.fromCharCode(sample % 256);
header += String.fromCharCode(Math.floor(sample / 256));
}
return 'data:audio/wav;base64,' + btoa(header);
}
function generateTone(freq, sampleRate, duration){
var tone = []
for(var i = 0; i < duration * sampleRate; ++i){
tone.push(Math.sin(2 * Math.PI * i / (sampleRate/freq)));
}
return tone;
}
$(document).ready(function(){
$("#body").html("Sounds...");
var sampleRate = 44100; // hz
var freq = 400; // hz
var duration = 2; // seconds
var tone = generateTone(freq, sampleRate, duration);
var base64EnodedTone = encodeAudio16bit(tone, sampleRate);
var audioPlayer = $('<audio>').attr({ src: base64EnodedTone,
controls:true
});
$("#body").append(audioPlayer);
$("#body").append("<p>done<p>");
});
</script>
</head>
<body>
<div id="body" ></div>
</body>
</html>