简体   繁体   中英

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

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

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.

src= is meant to point to a URL, not be filled with binary data.

You have to either

  • send binary data, with an appropriate header
  • OR send a HTML fragment, referencing (but not containing ) the binary data.

Not both at the same time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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