php - 需要将工作 php 代码转换为函数(随机合并 mp3 文件)

标签 php function file audio merge

一个教育游戏使用一堆 25 个以数字为名称的 mp3 文件(1.mp3、2.mp3、3.mp3 等)。它们一个接一个地播放,并在主声音中随机添加一个音频前缀。

我用过这个帖子:Merge two mp3 php合并文件。现在,我为每个播放的轨道准备了三个 mp3 文件:主声音文件(1.mp3、2.mp3 等)和两个辅助文件 s_prefix.mp3(要添加声音)和 s_blank.mp3 (增加沉默)。我用这些辅助文件创建了一个数组,将它们随机化并添加到主音频之前。

<?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');
}

关于php - 需要将工作 php 代码转换为函数(随机合并 mp3 文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55402536/

相关文章:

arrays - 如何在 F# 中定义不同签名的函数数组

javascript - 根据函数的初始化方式,ES6 导入的行为有所不同

python - Python 类中的作用域

用于匹配搜索间隔的 Java 文件名过滤器

PHP:将 notify.php 从 HTTP 1.0 更改为 1.1 失败

php - gif 文件从 php 到 iphone

perl - 使用 Go 将文本文件从硬盘读取到内存的最快方法是什么?

java - 如何使用 Java 压缩/解压缩文件夹及其所有文件和子目录?

使用 ajax 提交时,PHP post 请求总是返回 400

php - 从 WooCommerce 主侧边栏中删除元素符号点