简体   繁体   English

div中的标题(“Content-Type:audio / mpeg”)

[英]header(“Content-Type: audio/mpeg”) in div

i have a file speakWord.php: 我有一个文件speakWord.php:

<?php
header("Content-Type: audio/mpeg");
$voice = file_get_contents('http://translate.google.com/translate_tts?tl=' . urlencode($_POST['language']) . '&q=' . urlencode($_POST['word']) . '');
?>

<audio controls="controls" autoplay>
    <source src="<?php echo $voice; ?>"  />
</audio>

Now i want to use jquery to load the result of this mp3 file and output it in a div: 现在我想使用jquery加载这个mp3文件的结果并将其输出到div中:

$("#speakWord")
.load("speakWord.php", {
    language: "nl",
    word: "test"
});

When i check the source of the div, it becomes something weird like: 当我检查div的来源时,它会变成奇怪的东西:

<source src="��@��#a�F(��y2i���Ǵ1�L A�@���'!D����΂��8" �="">

I think the header information is lost in speakWord.php when loaded in a div, i think im missing a part.. 我认为在装入div时,speakWord.php中的标题信息丢失了,我想我错过了一个部分..

If you really have to proxy it over your script (if there was any Google API auth token), then package up the binary data into a base64 data: URL for the src= attribute. 如果您真的必须通过脚本代理它(如果有任何Google API身份验证令牌),则将二进制数据打包为base64 data: src=属性的URL。

<?php
   // Content-Type for whole PHP output remains text/html 
   $voice = file_get_contents('http://translate.google.com/translate_tts?tl=' . urlencode($_POST['language']) . '&q=' . urlencode($_POST['word']) . '');
?>
<audio controls="controls" autoplay>
    <source src="data:audio/mpeg;base64,<?php echo base64_encode($voice); ?>"  />
</audio>

However that's a larger transfer. 然而,这是一个更大的转移。

The actual answer, as already given, is that you should separate content types. 已经给出的实际答案是您应该分离内容类型。 Your script should only return the audio data, not mixed html and binary content. 您的脚本应仅返回音频数据,而不是混合的html和二进制内容。 In essence it should just be: 本质上它应该只是:

<?php
  header("Content-Type: audio/mpeg");
  readfile('http://translate.google.com/translate_tts?tl=' . urlencode($_POST['language']) . '&q=' . urlencode($_POST['word']) . '');
?>

So instead you had to construct the <audio> tag via jQuery (insted of ajax loading it): 所以你必须通过jQuery构建<audio>标签(加载它的ajax):

$("#speakWord")
.html("<audio... src='speakWord.php?language=nl&word=test'></audio>");

So this src= attribute retrieves the output from your speakWord script, which in turn pulls it over from the translate service. 所以这个src=属性从speakWord脚本中检索输出,然后从translate服务中提取它。

src= is meant to point to a URL, not be filled with binary data. src=意味着指向一个URL,而不是用二进制数据填充。

You have to either 你必须要么

  • send binary data, with an appropriate header 使用适当的标头发送二进制数据
  • OR send a HTML fragment, referencing (but not containing ) the binary data. 或者发送一个HTML片段,引用(但不包含 )二进制数据。

Not both at the same time. 不是两个在同一时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM