我需要动态嵌入返回的音频数据,以便我可以播放请求的mpegs。
<embed src=
正在寻找文件路径,但我本地没有文件。
我发出了一个成功请求,返回audio / mpeg二进制数据:
$.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\" />";
}
);
如何使用该数据创建音频元素?
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);
编辑:如果直接从我的服务器上拉,我就能播放音频:
var returned_data = '/recordings/subjects/Wo_I.mp3';
document.getElementById("audio").innerHTML=
"<embed src=\""+returned_data+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
资源被解释为文档但使用MIME类型audio / mpeg传输:“http://melon.localhost/recordings/subjects/Wo_I.mp3”。
如果我在上面的PHP中使用base64进行编码...
'<embed src="data:audio/mpeg;base64,'+returned_data+'" hidden="true" autostart="true" loop="false"/>'
它使用MIME传输到audio / mpeg,但没有音乐播放。
资源被解释为Document但是使用MIME类型audio / mpeg传输:“data:audio / mpeg; base64,”。
答案 0 :(得分:1)
您可以使用PHP对音频文件进行base64编码,并将数据直接放入<embed>
标记。
在PHP中,发送header("Content-type: text/plain");
(因为您现在将发送纯文本)并使用base64_encode()
对音频文件进行base64编码:
echo base64_encode($binary_data);
然后在JavaScript中,您可以将其直接放入<embed>
标记:
elem.innerHTML = '<embed src="data:audio/mpeg;base64,'+returned_data+'" hidden="true" autostart="true" loop="false"/>';
请注意,当您使用base64编码时,其大小约为其二进制等效值的4/3,因此,如果您要传输大型音频文件,则最好使用Javascript进行编码。因为遗憾的是,没有原生的javascript函数来base64编码二进制数据,here's an example你怎么做。