首页 > 解决方案 > 在目录中查找一个mp4文件,并在php中转换为mp3后将其发送到不同的目录?

问题描述

我有一个名为incoming_folder的目录,其中有一个mp4 文件。

我想通过php代码实现的是扫描一个incoming_folder目录,查找一个mp4文件,转换成mp3后发送到outing_folder 。

从技术上来说, outcoming_folder应该有来自incoming_folder的mp3 版本的mp4

这是我想要的图形表示:

在此处输入图像描述

尽管它扫描了incoming_folder目录但没有通过ffmpeg进行转换,但尝试使用以下代码。

<?php
$dir    = 'in_folder';  /* Place where mp4 file is present */
$files1 = scandir($dir);
print_r($files1);    /* It lists all the files in a directory including mp4 file*/

$destination = 'out_folder';  /* Place where mp3 file need to be send after conversion from mp4 */

    <?php
    foreach($files1 as $f)
    {
      $parts = pathinfo($f);

      switch($parts['extension'])
      {
        case 'mp4' :
          system('ffmpeg -i '.$f.' -map 0:2 -ac 1 '.$destination.DS. $parts['filename'].'.mp3', $result);

          if ($result) {
            // Do something with result if you want
            // log for example
          }
          break;

        case 'mp3' :
          // copy($f, $destination. DS . $parts['filename']. '.' . $parts['extension']);
          copy($f, $destination.DS.$parts['filename'].'.mp3');
          break;  
      }
    }
    ?>

问题陈述:

我想知道我应该在 php 代码中进行哪些更改,以便文件的转换从incoming_folder发生并且它应该转到outside_folder

标签: phpaudiovideoffmpeg

解决方案


我看到的主要问题是您仅将文件名传递给 ffmpeg,而不是文件路径。您需要$dir.DS在文件名前添加。

<?php
$filePath = $dir . DS . $f;
system('ffmpeg -i ' . $filePath . ' -map 0:2 -ac 1 ' . $destination . DS . $parts['filename'] . '.mp3', $result);

在我修复它之后,ffmpeg 失败了,抱怨你的流图参数。我把它们改成了这个,它起作用了,YMMV。

<?php           
system('ffmpeg -i ' . $filePath . ' -acodec libmp3lame -ac 2 -ab 160k -ar 48000 ' . $destination . DS . $parts['filename'] . '.mp3', $result);

编辑:完整更新的代码

<?php
const DS = '/';
$dir    = 'in_folder';  /* Place where mp4 file is present */
$files1 = scandir($dir);
print_r($files1);    /* It lists all the files in a directory including mp4 file*/

$destination = 'out_folder';  /* Place where mp3 file need to be send after conversion from mp4 */


foreach ($files1 as $f)
{

    $parts = pathinfo($f);
    switch ($parts['extension'])
    {
        case 'mp4' :
            $filePath = $dir . DS . $f;
            system('ffmpeg -i ' . $filePath . ' -acodec libmp3lame -ac 2 -ab 160k -ar 48000 ' . $destination . DS . $parts['filename'] . '.mp3', $result);

            if ($result)
            {
                // Do something with result if you want
                // log for example
            }
            break;

        case 'mp3' :
            // copy($f, $destination. DS . $parts['filename']. '.' . $parts['extension']);
            copy($f, $destination . DS . $parts['filename'] . '.mp3');
            break;
    }
}

推荐阅读