且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在php目录中查找特定文件类型,并在转换后将其发送到其他目录

更新时间:2023-02-08 18:19:05

以为这就是您想要的:

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

$destination = 'your new destination';

foreach($files1 as $f)
{
  $parts = pathinfo($f);
  if ($parts['extension'] = 'mp3';
  {
    // copy($f, $destination. DS . $parts['filename']. '.' . $parts['extension']);
    rename($f, $destination. DS . $parts['filename']. '.mp3');
  }
}
?>

文档路径信息

通过转换进行

我认为您可以像这样直接导出mp3

I think you can directly export your mp3 like this

foreach($files1 as $f)
{
  $parts = pathinfo($f);
  if ($parts['extension'] = 'mp4';
  {
    // $result : the last line of the command output on success, and FALSE on failure. Optional.
    system('ffmpeg -i '.$f.' -map 0:2 -ac 1 '.$destination.DS. $parts['filename'].'.mp3', $result);
  }

  // See: https://www.php.net/manual/en/function.system.php
  if ($result === false) {
    // Do something if failed
    // log for example
  } else {
    // command completed with code : $result
    // 0 by convention for exit with success EXIT_SUCCESS
    // 1 by convention for exit with error EXIT_ERROR
    // https://***.com/questions/12199216/how-to-tell-if-ffmpeg-errored-or-not
  }
}

文档系统

或者执行第一个循环来转换mp4,然后执行第二个循环来复制mp3

or do a first loop too convert mp4, and a second loop to copy mp3

全部

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

  switch(strtolower($parts['extension']))
  {
    case 'mp4' :
      // $result : the last line of the command output on success, and FALSE on failure. Optional.
      system('ffmpeg -i '.$f.' -map 0:2 -ac 1 '.$destination.DS. $parts['filename'].'.mp3', $result);

      // See: https://www.php.net/manual/en/function.system.php
      if ($result === false) {
        // Do something if failed
        // log for example
      } else {
        // command completed with code : $result
        // 0 by convention for exit with success EXIT_SUCCESS
        // 1 by convention for exit with error EXIT_ERROR
        // https://***.com/questions/12199216/how-to-tell-if-ffmpeg-errored-or-not
      }
      break;

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

编辑1 : 更正strtolower($parts['extension'])以检查文件的扩展名不区分大小写.

Edit 1 : correction strtolower($parts['extension']) to check the extension of the file none case-sensitive.

或这样:

strtolower(pathinfo("/path/file.mP4", PATHINFO_EXTENSION)) == ".mp4"

无需使用preg_matchregexp,因为pathinfo是执行此功能的预制函数,并且除非您使用诸如.tar.gz之类的双扩展名,否则它都可以正常工作.

There is no need to use preg_match and regexp because pathinfo is a pre-made function to do the job and it works fine unless you use double named extension like .tar.gz for example.

regular-expression-to-detect-a-file-extension

编辑2 :使用rename而不是copy移动mp3.

Edit 2 : Use rename instead of copy to move mp3.