Skip to content

Instantly share code, notes, and snippets.

@jeffreycrow
Created February 4, 2012 19:14
Show Gist options
  • Select an option

  • Save jeffreycrow/1739558 to your computer and use it in GitHub Desktop.

Select an option

Save jeffreycrow/1739558 to your computer and use it in GitHub Desktop.
This code retrieves an mp3 from Google Text-to-Speech for a query and converts it to oggvorbis using ffmpeg so it's cross-browser compatible. You can use it in a src attribute of an <audio> tag like you would with the Google TTS API. Uses STDIN/OUT, not f
<?php
// ffmpeg command. currently converts mp3 to oggvorbis
$ffmpeg_cmd = "ffmpeg -i - -acodec libvorbis -f ogg -";
// Set headers for ogg binary data
header("Accept-Ranges: bytes");
header("Content-Type: application/ogg");
header("Content-Transfer-Encoding: binary");
// Get mp3 data from Google TTS
$qs = http_build_query(array("ie" => "utf-8","tl" => $_GET["tl"], "q" => $_GET["q"]));
$ctx = stream_context_create(array("http"=>array("method"=>"GET","header"=>"Referer: \r\n")));
$soundfile = file_get_contents("http://translate.google.com/translate_tts?".$qs, false, $ctx);
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to
);
$process = proc_open($ffmpeg_cmd, $descriptorspec, $pipes);
if (is_resource($process)) {
// $pipes now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
// Any error output will be appended to /tmp/error-output.txt
fwrite($pipes[0], $soundfile);
fclose($pipes[0]);
$oggOutput = stream_get_contents($pipes[1]);
fclose($pipes[1]);
// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$return_value = proc_close($process);
echo $oggOutput;
}
?>
@jeffreycrow
Copy link
Author

Based on this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment