需要将工作php代码转换为函数(随机合并mp3文件)
一个教育游戏使用一堆25个mp3文件,并以数字作为名称(1.mp3、2.mp3、3.mp3等)。它们一个接一个地播放,并随机在主声音中添加音频前缀 我用这个帖子:合并文件。现在,我有三个mp3文件用于每个播放的曲目:主声音文件(1.mp3、2.mp3等)和两个辅助文件s_prefix.mp3(添加声音)和s_blank.mp3(添加静音)。我用这些辅助文件创建了一个数组,将它们随机化并添加到主音频之前需要将工作php代码转换为函数(随机合并mp3文件),php,function,file,audio,merge,Php,Function,File,Audio,Merge,一个教育游戏使用一堆25个mp3文件,并以数字作为名称(1.mp3、2.mp3、3.mp3等)。它们一个接一个地播放,并随机在主声音中添加音频前缀 我用这个帖子:合并文件。现在,我有三个mp3文件用于每个播放的曲目:主声音文件(1.mp3、2.mp3等)和两个辅助文件s_prefix.mp3(添加声音)和s_blank.mp3(添加静音)。我用这些辅助文件创建了一个数组,将它们随机化并添加到主音频之前 <?php $a = $b = $c = 1; $arr = ar
<?php
$a = $b = $c = 1;
$arr = array("mp3files/prefix.mp3", "mp3files/blank.mp3");
?>
<table>
<tr>
<td><a href="
<?php
// first audio
$s_rand = $arr[rand(0,sizeof($arr)-1)];
file_put_contents('mp3files/comb' . $a++. '.mp3', file_get_contents($s_rand) . file_get_contents('mp3files/' . $b++. '.mp3'));
echo ('mp3files/comb' . $c++. '.mp3');
?>
">Example text1</a></td>
</tr>
<tr>
<td><a href="
<?php
// second audio
$s_rand = $arr[rand(0,sizeof($arr)-1)];
file_put_contents('mp3files/comb' . $a++. '.mp3', file_get_contents($s_rand) . file_get_contents('mp3files/' . $b++. '.mp3'));
echo ('mp3files/comb' . $c++. '.mp3');
?>
">Example text2</a></td>
</tr>
<tr>
<td><a href="
<?php
// third etc... audio
$s_rand = $arr[rand(0,sizeof($arr)-1)];
file_put_contents('mp3files/comb' . $a++. '.mp3', file_get_contents($s_rand) . file_get_contents('mp3files/' . $b++. '.mp3'));
echo ('mp3files/comb' . $c++. '.mp3');
?>
">Example text3</a></td>
</tr>
</table>
它工作得很好,但即使对我来说,它看起来相当笨重,而且需要多次重复。有人可以简化代码,或者最好创建一个php函数来重申它。您需要使用循环
<?php
$start_file = 1; //first file
$files_count = 3; //count of all educational files
$prefix = array("mp3files/prefix.mp3", "mp3files/blank.mp3");
for ($i = $start_file; $i <= $files_count; $i++){
$s_rand = $prefix[rand(0,sizeof($prefix)-1)];
file_put_contents('mp3files/comb' . $i. '.mp3',
file_get_contents($s_rand) .
file_get_contents('mp3files/' . $i. '.mp3'));
echo ('mp3files/comb' . $i. '.mp3');
}