doufeng1249 2012-01-18 21:18
浏览 588
已采纳

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

i have a file 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:

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

When i check the source of the div, it becomes something weird like:

<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..

  • 写回答

2条回答 默认 最新

  • dongpiao0731 2012-01-18 21:28
    关注

    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.

    <?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. 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):

    $("#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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?