Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I transcode a file with FFMPEG and stream the output file in the response of a Java servlet?
    text
    copied!<p>Basically, this is what I'm trying to do: 1. User passes a URL as a GET parameter to my servlet. 2. Servlet uses a ProcessBuilder to convert the media contained in that URL to a valid media format (ie: MP3). 3. The servlet streams the output file being transcoded by FFMPEG back to the browser.</p> <p>1 and 2 work fine, but it is 3 I am having a problem with. The best I can do is create a FileInputStream to the output file being transcoded and send that as the response but it is not working. My guess is that it is because the file is being written as I'm trying to stream it.</p> <p>Is there anyway to intercept the output file argument in FFMPEG and read it into an InputStream? In my mind it does not seem that it should be difficult to take input file A, transcode it to output file B, and then stream output file B back to the client, on the fly.</p> <pre><code>ProcessBuilder pb = new ProcessBuilder("ffmpeg.exe", "-i", url, "file.mp3"); Process p = pb.start(); final InputStream inStream = p.getErrorStream(); new Thread(new Runnable() { public void run() { InputStreamReader reader = new InputStreamReader(inStream); Scanner scan = new Scanner(reader); while (scan.hasNextLine()) { System.out.println(scan.nextLine()); } } }).start(); ServletOutputStream stream = null; BufferedInputStream buf = null; try { stream = response.getOutputStream(); File mp3 = new File(file.mp3"); //set response headers response.setContentType("audio/mpeg"); response.addHeader("Content-Disposition", "attachment; filename=file.mp3"); response.setContentLength(-1); //response.setContentLength((int) mp3.length()); FileInputStream input = new FileInputStream(mp3); buf = new BufferedInputStream(input); int readBytes = 0; //read from the file; write to the ServletOutputStream while ((readBytes = buf.read()) != -1) { stream.write(readBytes); } } catch (IOException ioe) { throw new ServletException(ioe.getMessage()); } finally { if (stream != null) { stream.close(); } if (buf != null) { buf.close(); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload