Как конвертировать mp4 файлы в mp3 по нажатию кнопки, используя ffmpeg / php? - PullRequest
0 голосов
/ 03 июня 2019

Я работаю над кодом php, как показано ниже, где я конвертирую mp4 файлы в mp3 , используя системную команду ffmpeg (в приведенном ниже примере case),

<?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 , преобразование обычно происходит при обновлении страницы.

Как только преобразование завершено, я разбираю все в таблицу, как показано ниже:

<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) .

enter image description here

1 Ответ

1 голос
/ 03 июня 2019

Лучшим способом является использование XMLHttpRequest с лучшим примером здесь AJAX - Ответ сервера

Создайте функцию 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>

Добавьте куда-нибудь что-нибудь для обработки ответа сервера так, как вы хотите;пример:

<div id="myResponse"></div>

Изменить кнопку для вызова функции javascript onclick="go('<?php echo $key; ?>', this); return false;":

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

Потратьте время, чтобы узнать, как работает вызов Ajax, очень важно общатьсяс сервером, если вы не используете форму

Вы можете использовать JQuery, но лучше без;)

Редактировать

Использование формы, вы можете сделать это:

<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")

и page.php или your_encoder.php, как вы хотите для вызова Ajax:

// 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.

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

Редактировать :

Я знаю, что это адаптировано из вашего вопроса предварительного просмотра , но этот код "неверен", работает, нет проблем, но его можно оптимизировать какэто:

от ...

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

... до

<?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));
?>
...