0
I’m developing a script of a captcha simple in PHP and I challenged myself to be able to generate an audio file to help people with visual impairments.
I didn’t know exactly how to do this, but I created an audio file for each letter of the alphabet and called it 'letter name. mp3 (example: w.mp3'), and, in an archive PHP called 'audio php.', designed to create the final audio file, I took the letters from the captcha and added the audio of each letter using the functions file_get_contents()
and fwrite()
, native to the PHP; to my surprise, it worked exactly as I wanted it.
My question is, although it worked, is it correct to do so? Reading the contents of one file and writing it in another is simple in text files and similar, but in more complex files like audios, I have my doubts if it is ideal. If yes, it is recommended?
audio php.:
<?php
session_start(); //início da sessão
$vetorLetras = str_split($_SESSION["captcha"]); //código do CAPTCHA
$arquivo = "audios".DIRECTORY_SEPARATOR.session_id().".mp3"; //nome do arquivo a ser criado
$f = fopen($arquivo, "a+"); //arquivo é criado
for ($i = 0; $i < 5; $i++) {
//a cada repetição o arquivo recebe o conteúdo do áudio de uma letra
$x = file_get_contents("audios".DIRECTORY_SEPARATOR.$vetorLetras[$i].".mp3");
fwrite($f, $x);
}
fclose($f); //arquivo é fechado
//força-se o download do arquivo
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: binary");
header("Content-disposition: attachment; filename=\"audio.mp3\"");
readfile($arquivo);
//arquivo é excluído
unlink($arquivo);
?>
Dear Fernando, it doesn’t make sense, most of the files have a type of input/ header, your problem doesn’t even have to do with fwrite or php, the question is to understand how the file format works, in the case mp3, if it were only to merge things would be OK, but it is not, so there are Codecs (encoders/decoders) formats, in case there is a tool that can use on most servers (usually have in the repository of your linux server if it is not Shared or then you will have to ask the support to install) that is the FFMPEG that will help you in this...
– Guilherme Nascimento
... but ffmpeg and servers is not question scope here on the site, so I’m just commenting instead of answering, what will solve you easy is to install ffmpeg and learn how to use it (it is via command line in php to run a command line of another program use the
exec()
).– Guilherme Nascimento
Simm until it works... but has reservations, MP3 was created to be independent frame, so it is possible to cut the audio directly without doing Decode, if the bit rate of your files do not vary OK, otherwise there will be inconsistencies in each header, in the end you may have a file with wrong information
– ederwander