title: How to download & serve youtube-dl mp3 (on the fly) to the user?
body: <p><br>
  I need a way to download &amp; convert youtube videos to mp3 on the fly. I mean without having the user wait till the file is downloaded on my server and then serve it.<br>
  I'm currently using the following function to download the mp3 file to my server.It takes the video link as a param and returns the downloaded file location. It also checks if the file is already downloaded and returns its location if yes.</p>
  
  <pre><code>function downloadMP3($videolink){
      parse_str( parse_url( $videolink, PHP_URL_QUERY ), $parms );
      $id = $parms['v'];
      $output = "download/".$id.".mp3";
      if (file_exists($output)) {
          return $output;
      }else {
          $descriptorspec = array(
              0 =&gt; array(
                  "pipe",
                  "r"
              ) , // stdin
              1 =&gt; array(
                  "pipe",
                  "w"
              ) , // stdout
              2 =&gt; array(
                  "pipe",
                  "w"
              ) , // stderr
          );
          $cmd = 'youtube-dl --extract-audio --audio-quality 0 --audio-format mp3 --output download/"'.$id.'.%(ext)s" '.$videolink;
          $process = proc_open($cmd, $descriptorspec, $pipes);
          $errors = stream_get_contents($pipes[2]);
          fclose($pipes[2]);
          $ret = proc_close($process);
          if ($errors) {
              //print($errors);
          }
          return $output;
      }
  }
  </code></pre>
  
  <p>Now whenever the user tries to download a file, I simply get the link and pass it to the function and use the following code to serve the file :</p>
  
  <pre><code>$downloadpath = downloadMP3($videolink);
  $song_name = "song";
  header('X-Accel-Redirect: /' . $downloadpath);
  header("Content-Type: audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3");
  header('Content-length: ' . filesize($_SERVER["DOCUMENT_ROOT"]."/".$downloadpath));
  header('Content-Disposition: attachment; filename="'.$song_name.'.mp3"');
  header('X-Pad: avoid browser bug');
  header('Cache-Control: no-cache');
  </code></pre>
  
  <p>I've looked online and found that people use <code>youtube-dl -o - VIDEO_URL</code> with <code>passthru()</code> and it works to download videos but not mp3 files.<br>
  So does anyone have any idea how to accomplish that ?</p>