Is there less memory, an extensive or more efficient way to merge MP3s than file_get_contents?

I need to combine several mp3 files into one.

I am currently doing this:

$combinedFiles = "";
$dir = $_POST['dir'];

if ($handle = opendir($dir)) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            $combinedFiles .= file_get_contents(urldecode($dir."/".$entry));
        }
    }

    closedir($handle);
}


file_put_contents("mp3/".$dir.".mp3",   ($combinedFiles));

If I do this:

ini_set('memory_limit', -1);

it works. I tried to set this limit to 4 MB and it does not produce memory errors, but the file is not created. Without setting any restrictions and leaving the default, I get memory memory errors. I do not want to leave it on -1, as I read that this is bad practice and can lead to problems.

Thank you (the error does not come anywhere in the code, I run it only).

Edit: even when setting to 8 GB, which is my computer memory, it does not work.

+4
3

?

<?php
$dir = $_POST['dir'];

if ($handle = opendir($dir))
{
    $outFd = fopen(sprintf("mp3/%s.mp3", $dir), 'wb');

    while (false !== ($entry = readdir($handle)))
    {
        if ($entry != "." && $entry != "..")
        {
            $path = urldecode(sprintf("%s/%s", $dir, $entry));

            $inFd = fopen($path, 'rb');
            stream_copy_to_stream($inFd, $outFd);
            fclose($inFd);
        }
    }

    fclose($outFd);

    closedir($handle);
}

, , . .

, , , ? stream_copy_to_stream().

, stream_set_chunk_size(), , MP3 (4-5Mb tops). / , stream_copy_to_stream(), .

, .

+1
+1

In your example, you copy all the files to memory and write them back to disk when performing the task.

My advice:

  • Copy the first file to a new location
  • Get contents from the second file and add it to the copied file (file_put_contens FILE_APPEND)
  • Discard variable with contents
  • continue from step 2 until this is done
+1
source

Source: https://habr.com/ru/post/1629732/


All Articles