I use this code to generate a audio element from byte , it create a simple wav sound , I am able to play that in google chrome or firefox of DESKTOP , but when I want to play that in Google Chrome Mobile , it play nothing , where is the problem , I am able to play wav file easly but I am not able to play music from binary data in 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>