GOTO

Tuesday, April 20, 2010

Concatenating audio files in php

Hi everybody,

yesterday I was working on a spelling function in php. The base idea was taking each letter of the word to spell and playing the relative sound (a voice that pronounces a letter). Letter's index and word's name was passed by GET method.

session_start();
$in=$_GET['index'];
$var=$_SESSION[$_GET['name']];
$filename = $var[$in].".mp3";

header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename=sound');
header("Content-Type: audio/mp3");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. filesize($filename));
readfile($filename);


So, in that case, I needed to create an audio tag ( I'm updated, I'm using html5 :) ) for each audio file and play them using javascript. But there's another more simple way to do what I wanted: concatenate all files! How can we do that? It's very simple, we have only to call readfile function for each file and set the content length as the sum of all file sizes. Here is an example (2 files to spell 'hi!'):

session_start();
$filename1 = "h.mp3";
$filename2 = "i.mp3";

$size=filesize($filename1)+filesize($filename2);

header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename=sound');
header("Content-Type: audio/mp3");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '.$size);
readfile($filename1);
readfile($filename2);


If you want to use audio tags, remember that mp3 are only supported by Chrome and Safari4. Firefox and Opera supports wave files. Don't try to use ogg files: concatenating operation isn't so simple..There are also some problems with the use of audio tags, but...I'll deal with it in another post...

::See you next post::

No comments:

Post a Comment