I would like to generate a sine tone in php. But constructing my wav I need to give the values in bytes. I don't know how to do that:
Here is the code I have:
$freqOfTone = 440;
$sampleRate = 44100;
$samplesCount = 80000;
$amplitude = 0.25 * 32768;
$w = 2 * pi() * $freqOfTone / $sampleRate;
//$dataArray = new
$text = "RIFF"
."80036"
."WAVE"
."fmt "
."16"
."1"
."1"
."44100"
."44100"
."1"
."8"
."data"
."80000";
for ($n = 0; $n < $samplesCount; $n++)
{
$text .= (int)($amplitude * sin($n * $w));
}
$myfile = fopen("sine.wav", "w") or die("Unable to open file!");
fwrite($myfile, $text);
fclose($myfile);
The problem is that you algorithm writes the numbers as text. Whereas a
.wav
file encodes the data binary.You can use for instance
pack
to group data.This produces this file.
Note that you can't just reuse the above header. Some aspects were hardcoded that differ (like the size of the file, number of channels, bitrate, etc.). But if one reads the documentation, one can easily modify the header accordingly.