Search code examples
spring-bootffmpeg

how to Extract Audio from video with spring boot java in linux or windows system with ffmpeg coding part need guidance


I got this command but don't know the how to configure it for project on command line?

String[] command = {"-y", "-i", filename, "-vn", "-ar", "44100", "-ac", "2", "-b:a", "256k", "-f", "mp3" + fileStorageLocation};


Solution

  • Runtime runtime = Runtime.getRuntime();
            String[] command = {"ffmpeg",
                    "-i", DIRECTORY + fileName, "-vcodec", "copy", "-an", DIRECTORY+"no_" + fileName
            };
            try {
                Process process = runtime.exec(command);
                LOGGER.info("Process"+process);
                int exitValue = process.waitFor();
                LOGGER.info("Started video with exit code: {}", exitValue);
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
                LOGGER.info("stdInput" +stdInput.readLine());
                BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                LOGGER.info("stdError" +stdError);
    
                // read the output from the command
                StringBuilder normalOutputBuffer = new StringBuilder();
                String line;
                while ((line = stdInput.readLine()) != null) {
                    LOGGER.info("This is ffmpeg try  while block");
                    normalOutputBuffer.append(line);
                    if (!line.contains("Done:")) {
                        normalOutputBuffer.append("\n");
                    }
    
                }
                if (!normalOutputBuffer.toString().isEmpty()) {
                    LOGGER.info("video generation ended successfully. \n {}", normalOutputBuffer.toString());
                }
    
                // read any errors from the command
                StringBuilder errorOutputBuffer = new StringBuilder();
                while ((line = stdError.readLine()) != null) {
                    errorOutputBuffer.append(line);
                    errorOutputBuffer.append("\n");
                }
                if (!errorOutputBuffer.toString().isEmpty()) {
                    LOGGER.info("video generation ended with failure. \n {}", errorOutputBuffer.toString());
                }
    
            } catch (InterruptedException e) {
                LOGGER.error("video generation was interrupted.");
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                LOGGER.error("Error during video generation.");
                e.printStackTrace();
                return false;
            }
    
            return true;