首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用ffmpeg/php按钮将mp4文件转换为mp3?

如何使用ffmpeg/php按钮将mp4文件转换为mp3?
EN

Stack Overflow用户
提问于 2019-06-03 15:33:42
回答 1查看 850关注 0票数 0

我正在编写一个php代码,如下所示,我使用系统命令ffmpeg(在下面的case语句中)将mp4文件转换为mp3。

代码语言:javascript
复制
<?php 

$mp4_files = preg_grep('~\.(mp4)$~', scandir($src_dir)); 

foreach ($mp4_files as $f)
 {

     $parts = pathinfo($f);
     switch ($parts['extension'])
     {
         case 'mp4' :
             $filePath = $src_dir . DS . $f;
             system('ffmpeg -i ' . $filePath . ' -map 0:2 -ac 1 ' . $destination_dir . DS . $parts['filename'] . '.mp3', $result);  // Through this command conversion happens. 
     }
 }

$mp3_files = preg_grep('/^([^.])/', scandir($destination_dir));

?>

转换后,mp3文件将进入destination_dir。如果新的mp4文件到达$src_dir,则转换通常在刷新页面时进行。

一旦转换完成,我将将所有内容解析为表,如下所示:

代码语言:javascript
复制
<table>
   <tr>
      <th style="width:8%; text-align:center;">House Number</th>
      <th style="width:8%; text-align:center;">MP4 Name</th>
      <th style="width:8%; text-align:center;" >Action/Status</th>
   </tr>
   <?php
      $mp4_files = array_values($mp4_files);
      $mp3_files = array_values($mp3_files);
      foreach ($programs as $key => $program)    { 
         $file = $mp4_files[$key];     
         $file2 = $mp3_files[$key];   // file2 is in mp3 folder
      ?>
   <tr>
      <td style="width:5%; text-align:center;"><span style="border: 1px solid black; padding:5px;"><?php echo basename($file, ".mp4"); ?></span></td> <!-- House Number -->
      <td style="width:5%; text-align:center;"><span style="border: 1px solid black; padding:5px;"><?php echo basename($file); ?></span></td> <!-- MP4 Name -->             
      <td style="width:5%; text-align:center;"><button style="width:90px;" type="button" class="btn btn-outline-primary">Go</button</td>  <!-- Go Button -->
   </tr>
   <?php } ?>
</table>

问题陈述:

我想知道我应该在上面的php代码中做哪些修改--单击Go按钮,将单个mp4转换为mp3

在单击Go按钮时,属于单个行的单个mp3文件(来自mp4)应该位于目标目录($destination_dir)中。

EN

回答 1

Stack Overflow用户

发布于 2019-06-03 17:56:47

最好的方法是使用XMLHttpRequest,这里有更好的示例,AJAX服务器响应

创建如下javascript函数:

代码语言:javascript
复制
<script>
  // Check if the window is loaded
  window.addEventListener('load', function () {

    // Function to call Ajax request to convert or move file
    var go = function(key, btn) {

      // Initialize request
      var xhttp = new XMLHttpRequest();

      // Execute code when the request ready state is changed and handle response.
      // Optional but recommended.
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          // Do what you want here with the response here
          document.getElementById('myResponse').innerHTML = this.responseText;

          // Disable the button to not clicking again
          // see https://www.w3schools.com/jsref/prop_pushbutton_disabled.asp
          btn.disabled = true;
         }
      };

      // Handle error message here
      // Optional but recommended.
      xhttp.onerror = function(event) {
        document.getElementById('myResponse').innerHTML = 'Request error:' + event.target.status;
      };

      // Create request to the server
      // Call the page that convert .mp4 or move .mp3
      xhttp.open('POST', '/your_convert_file.php', true);

      // Pass key or name or something (secure) to retrieve the file
      // and send the request to the server
      xhttp.send('key=' + key);
    }
 )};
</script>

根据需要添加一些东西来处理服务器的响应;例如:

代码语言:javascript
复制
<div id="myResponse"></div>

修改按钮以调用javascript函数onclick="go('<?php echo $key; ?>', this); return false;"

代码语言:javascript
复制
<button style="width:90px;" type="button" class="btn btn-outline-primary" onclick="go('<?php echo $key; ?>', this); return false;">Go</button>

花时间学习Ajax调用的工作原理,如果不使用表单,那么与服务器进行通信是非常重要的

你可以使用JQuery,但如果没有;)

编辑

使用表单,您可以这样做:

代码语言:javascript
复制
<form id="formId" action="your_page.php" method="post">

<!-- your table here -->

<input type="hidden" id="key" name="key" value="">
</form>

<script>
  var go = function(key) {
    document.getElementById('key').value = key;
    document.getElementById('formId').submit();
  }
</script>

编辑

$key替换为房屋编号basename($file, ".mp4")

以及Ajax调用所需的page.phpyour_encoder.php

代码语言:javascript
复制
// EXAMPLE FOR AJAX CALL

<?php 
// Get the unique name or key
$key = $_POST['key'];

// If key is empty, no need to go further.
if(empty($_POST['key'])) {
  echo "File name is empty !";
  exit();
}

// Can be secure by performing string sanitize
$filePath = $src_dir . DS . $key . '.mp4';

// Check if file exists
// echo a json string to parse it in javascript is better
if (file_exists($filePath)) {
    system('ffmpeg -i ' . $filePath . ' -map 0:2 -ac 1 ' . $destination_dir . DS . $parts['filename'] . '.mp3', $result);
    echo "The file $filePath has been encoded successfully.";
      . "<br />"
      . $result;
} else {
    echo "The file $filePath does not exist";
}
?>

如果使用form,则必须:

  1. 检查是否存在$_POST['key']
  2. 如果存在密钥,则执行编码。
  3. 发送您的新html表。
代码语言:javascript
复制
// EXAMPLE FOR FORM CALL

<?php
// Get the unique name or key
$key = $_POST['key'];

// If key is not empty.
if(!empty($_POST['key'])) {
  // do the encoding here like above
  // set message success | error
}

// display your html table and message here.
?>

编辑

我知道这是从您的预览问题中改编的,但是这段代码是“不正确的”,它可以工作,没有问题,但是可以像这样进行优化:

从..。

代码语言:javascript
复制
<?php 
// Here, you list only .mp4 in the directory
// see: https://www.php.net/manual/en/function.preg-grep.php
$mp4_files = preg_grep('~\.(mp4)$~', scandir($src_dir)); 

// Here you loop only on all .mp4 
foreach ($mp4_files as $f)
 {
     $parts = pathinfo($f);

     // Here, you check if extension is .mp4
     // Useless, because it is always the case.
     // see : https://www.php.net/manual/en/control-structures.switch.php
     switch ($parts['extension'])
     {
         case 'mp4' :
             $filePath = $src_dir . DS . $f;
             system('ffmpeg -i ' . $filePath . ' -map 0:2 -ac 1 ' . $destination_dir . DS . $parts['filename'] . '.mp3', $result);  // Through this command conversion happens. 
     }
 }

$mp3_files = preg_grep('/^([^.])/', scandir($destination_dir));
?>

..。至

代码语言:javascript
复制
<?php
// Here, you list only .mp4 on the directory
$mp4_files = preg_grep('~\.(mp4)$~', scandir($src_dir)); 

// Here you loop only on all .mp4 
foreach ($mp4_files as $f)
 {
     $filePath = $src_dir . DS . $f;

     // No more need to switch, preg_reg do the job before looping
     // Through this command conversion happens.
     system('ffmpeg -i ' . $filePath . ' -map 0:2 -ac 1 ' . $destination_dir . DS . pathinfo($f, 'filename') . '.mp3', $result);  
 }

$mp3_files = preg_grep('/^([^.])/', scandir($destination_dir));
?>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56430459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档