Ken
Ken

Reputation: 39

Need to convert working php code into function (merging mp3 files randomly)

An educational game uses a bunch of 25 mp3-files with numbers as names (1.mp3, 2.mp3, 3.mp3 etc.). They are played back one after another, and randomly an audio-prefix added to the main sound.

I used this post: Merge two mp3 php to merge files. Now I have three mp3 files for each played-back track: the main sound-file (1.mp3, 2.mp3, etc...) and two auxiliary files s_prefix.mp3 (with sound to be added) and s_blank.mp3 (to add silence). I create an array with these auxiliary files, randomize them and add before the main audio.

<?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>

It works fine, but even to my poor knowledge it looks pretty bulky and has to many repetitions. Could someone simplify the code or best of all create a php function to reiterate it.

Upvotes: 0

Views: 95

Answers (1)

Maksim
Maksim

Reputation: 2957

You need to use loops

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

Upvotes: 1

Related Questions