I need to dynamically embed returned audio data so I can play requested mpegs.
<embed src=
is looking for a file path, but I don't have files locally.
I make a successful request which returns audio/mpeg binary data:
$.get('testPHP.php?translate_tts?ie=utf-8&tl=zh-CN&q=你好',
function (returned_data) {
document.getElementById("audio").innerHTML=
"<embed src=\""+returned_data+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
}
);
How can I create the audio element with that data?
PHP:
<?php
header('Content-type: text/plain; charset=utf-8');
$params = http_build_query(array("ie" => $_GET['ie'],"tl" => $_GET["tl"], "q" => $_GET["q"]));
$ctx = stream_context_create(array("http"=>array("method"=>"GET","header"=>"Referer: \r\n"))); //create and return stream context
$soundfile = file_get_contents("https://translate.google.com/translate_tts?".$params, false, $ctx); //reads file into string (string with params[utf-8, tl, q], use include path bool, custom context resource headers)
header("Content-type: audio/mpeg");
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
header('Expires: 0');
echo base64_encode($binary_data);
Edit: I'm able to play audio if I pull directly from my server:
var returned_data = '/recordings/subjects/Wo_I.mp3';
document.getElementById("audio").innerHTML=
"<embed src=\""+returned_data+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
Resource interpreted as Document but transferred with MIME type audio/mpeg: "http://melon.localhost/recordings/subjects/Wo_I.mp3".
If I try encoding in base64 in PHP above...
'<embed src="data:audio/mpeg;base64,'+returned_data+'" hidden="true" autostart="true" loop="false"/>'
It's transferred with MIME to audio/mpeg, but no music plays.
Resource interpreted as Document but transferred with MIME type audio/mpeg: "data:audio/mpeg;base64,".