Combine an unknown number of .mp3 files

2019-08-04 00:45发布

问题:

I have this:

$number = 1;
$mp3 = file_get_contents("http://example.com/text=".$value);
$file = md5($value)."-".$number.".mp3";
file_put_contents($file, $mp3);
$number++;

Result: create abcdef-1.mp3, abcdef-2.mp3, abcdef-3.mp3.
Now I want to combine abcdef-1.mp3 with abcdef-2.mp3 and abcdef-3.mp3.

This works:

file_put_contents('abcdef.mp3',
file_get_contents('abcdef-1.mp3') .
file_get_contents('abcdef-2.mp3') .
file_get_contents('abcdef-3.mp3'));

But is not suitable for my code, because abcdef differ. Numbers too.

I've tried:

$number = 1;
$mp3 = file_get_contents("http://example.com/text=".$value);
$file = md5($value)."-".$number.".mp3";
file_put_contents($file, $mp3);
file_put_contents(md5($value).".mp3", file_get_contents($file));
$number++;

Result: create abcdef-1.mp3, abcdef-2.mp3, abcdef-3.mp3 and abcdef.mp3 but when I play it's only abcdef-1.mp3. Where is the problem?

回答1:

You can call file_put_contents with the FILE APPEND flag. Something like this should work

$number = 1;
$mp3 = file_get_contents("http://example.com/text=".$value);
$file = md5($value).".mp3";
file_put_contents($file, $mp3, FILE_APPEND);
$number++;