JAVA常用工具类-【5】FFMPEG转换、分割、合并音频

1、JAVA操作音频

package com.day.util;

import java.io.*;
import java.util.*;

public class AudioConvert {
    public static void main(String args[]) throws Exception {
        /**电脑上需要提前安装ffmpeg windows版*/
        //1.合并音频
        String tempPath=System.getProperty("user.dir").replaceAll("\\\\","/");
        String rootPath=tempPath+"/src/main/resources/static/server/audioMerge/";
        String cmd="ffmpeg -i \"concat:";
        List<File> files = MyFileOperate.filesGetByFolder(rootPath);
        for(int i=0;i<files.size();i++){
            File tempFile=files.get(i);
            cmd=cmd+tempFile.getName()+"|";
        }
        cmd=cmd+"\" -c copy "+rootPath+new Date().getTime()+"All.mp3";
        System.out.println(cmd);
        //拼接命令完毕后调用合并方法
        audioMerge(cmd,rootPath);
        String tempFolder="src/main/resources/static/server/audioConvert/";
        //2.实现音频格式批量转换
        List<File> fileList=MyFileOperate.filesGetByFolder(tempFolder);
        for(int i=0;i<fileList.size();i++){
            File tempFile=fileList.get(i);
            String targetFileName=tempFile.getName().substring(0,tempFile.getName().length()-4);
            changeWavTo16KPcm(tempFile.getName(),
                    tempFolder,
                    targetFileName+".pcm");
        }
        //3.切割PCM音频
        String tempFolderAnother="src/main/resources/static/server/audioConvert/";
        List<File> fileListAnother=MyFileOperate.filesGetByFolder(tempFolderAnother);
        for(int i=0;i<fileListAnother.size();i++){
            File tempFile=fileListAnother.get(i);
            String targetFileName=tempFile.getName().substring(0,tempFile.getName().length()-4);
            cutPCM("00:00:00",
                    "00:00:03",
                    tempFile.getName(),
                    tempFolderAnother,
                    targetFileName+"MyCut.pcm");
        }
    }
    /**1.合并音频*/
    public static void audioMerge(String cmd,String rootPath) {
        Runtime runTime = null;
        try {
            runTime = Runtime.getRuntime();
            long start = System.currentTimeMillis();
            //在指定目录下执行cmd命令,需要管理员权限才能执行
            Process process = runTime.exec("cmd /c "+cmd,null,new File(rootPath));
            //释放进程
            process.getOutputStream().close();
            process.getInputStream().close();
            process.getErrorStream().close();
            try {
                int mark=process.waitFor();
                System.out.println("返回的Mark值:"+mark);
                if(mark==0){
                    long end = System.currentTimeMillis();
                    System.out.println("合并成功, 耗时:" + (end - start) + "ms");
                }else{
                    System.out.println(rootPath+"合并失败, mark值:" +mark);
                }
            } catch (InterruptedException e) {
                System.out.println("发生错误异常"+e);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            runTime.freeMemory();
        }
    }
    /**2.Mp4转换为Mp3*/
    public static void changeMp4ToMp3(String srcFileName,String rootPath,String targetFileName) throws Exception {
        Runtime runTime = null;
        try {
            runTime = Runtime.getRuntime();
            long start=System.currentTimeMillis();
            //在指定目录下执行cmd命令
            System.out.println("cmd /c ffmpeg -y -i "+srcFileName+" "+targetFileName);
            Process process=runTime.exec("cmd /c ffmpeg -y -i "+srcFileName+" "+targetFileName,null,new File(rootPath));
            //释放进程
            //System.err.println("ffmpeg -y -i "+srcFileName+" -acodec pcm_s16le -f s16le -ac 1 -ar 16000 "+targetFileName);
            //System.err.println(rootPath);
            process.getOutputStream().close();
            process.getInputStream().close();
            process.getErrorStream().close();
            int mark=process.waitFor();
            if(mark==0){
                long end=System.currentTimeMillis();
                System.out.println("转换成功, 耗时:"+(end-start)+"ms");
                System.out.println("路径保存在: "+rootPath);
            }else{
                System.out.println(srcFileName+"操作失败,mark值:"+mark);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //run调用lame解码器最后释放内存
            runTime.freeMemory();
        }
    }
    /**3.Wav转换为16K的PCM*/
    public static void changeWavTo16KPcm(String srcFileName,String rootPath,String targetFileName) throws Exception {
        Runtime runTime = null;
        try {
            runTime = Runtime.getRuntime();
            long start=System.currentTimeMillis();
            //在指定目录下执行cmd命令
            Process process=runTime.exec("cmd /c ffmpeg -y -i "+srcFileName+" -acodec pcm_s16le -f s16le -ac 1 -ar 16000 "+targetFileName,null,new File(rootPath));
            //释放进程
            //System.err.println("ffmpeg -y -i "+srcFileName+" -acodec pcm_s16le -f s16le -ac 1 -ar 16000 "+targetFileName);
            //System.err.println(rootPath);
            process.getOutputStream().close();
            process.getInputStream().close();
            process.getErrorStream().close();
            int mark=process.waitFor();
            if(mark==0){
                long end=System.currentTimeMillis();
                System.out.println("转换成功, 耗时:"+(end-start)+"ms");
                System.out.println("路径保存在: "+rootPath);
            }else{
                System.out.println(srcFileName+"操作失败,mark值:"+mark);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //run调用lame解码器最后释放内存
            runTime.freeMemory();
        }
    }
    /**4.Mp3转换为16K的PCM*/
    public static void changeMp3To16KPcm(String srcFileName,String rootPath,String targetFileName)throws Exception {
        Runtime runTime = null;
        try {
            runTime = Runtime.getRuntime();
            long start=System.currentTimeMillis();
            //在指定目录下执行cmd命令
            Process process=runTime.exec("cmd /c ffmpeg -y -i "+srcFileName+" -acodec pcm_s16le -f s16le -ac 1 -ar 16000 "+targetFileName,null,new File(rootPath));
            //释放进程
            process.getOutputStream().close();
            process.getInputStream().close();
            process.getErrorStream().close();
            int mark=process.waitFor();
            if(mark==0){
                long end=System.currentTimeMillis();
                System.out.println("转换成功, 耗时:"+(end-start)+"ms");
                System.out.println("路径保存在: "+rootPath);
            }else{
                System.out.println(srcFileName+"操作失败,mark值:"+mark);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //run调用lame解码器最后释放内存
            runTime.freeMemory();
        }
    }
    /**5.PCM转换为16K的Wav*/
    public static void changePcmTo16KWav(String srcFileName,String rootPath,String targetFileName)throws Exception {
        Runtime runTime = null;
        try {
            runTime = Runtime.getRuntime();
            long start=System.currentTimeMillis();
            //System.out.println("cmd /c ffmpeg -y -f s16be -ac 1 -ar 16000 -acodec pcm_s16le -i "+srcFileName+" "+targetFileName);
            //在指定目录下执行cmd命令
            Process process=runTime.exec("cmd /c ffmpeg -y -f s16be -ac 1 -ar 16000 -acodec pcm_s16le -i "+srcFileName+" "+targetFileName,null,new File(rootPath));
            //释放进程
            process.getOutputStream().close();
            process.getInputStream().close();
            process.getErrorStream().close();
            int mark=process.waitFor();
            if(mark==0){
                long end=System.currentTimeMillis();
                System.out.println("转换成功, 耗时:"+(end-start)+"ms");
                System.out.println("路径保存在: "+rootPath);
            }else{
                System.out.println(srcFileName+"操作失败,mark值:"+mark);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //run调用lame解码器最后释放内存
            runTime.freeMemory();
        }
    }
    /**6.PCM转换为16K的Mp3*/
    public static void changePcmTo16KMp3(String srcFileName,String rootPath,String targetFileName)throws Exception {
        Runtime runTime = null;
        try {
            runTime = Runtime.getRuntime();
            long start=System.currentTimeMillis();
            //ffmpeg -y -f s16be -ac 1 -ar 16000 -acodec pcm_s16le -i 英文1分钟.pcm 1.mp3
            //System.out.println("cmd /c ffmpeg -y -f s16be -ac 1 -ar 16000 -acodec pcm_s16le -i "+srcFileName+" "+targetFileName);
            //在指定目录下执行cmd命令
            Process process=runTime.exec("cmd /c ffmpeg -y -f s16be -ac 1 -ar 16000 -acodec pcm_s16le -i "+srcFileName+" "+targetFileName,null,new File(rootPath));
            //释放进程
            process.getOutputStream().close();
            process.getInputStream().close();
            process.getErrorStream().close();
            int mark=process.waitFor();
            if(mark==0){
                long end=System.currentTimeMillis();
                System.out.println("转换成功, 耗时:"+(end-start)+"ms");
                System.out.println("路径保存在: "+rootPath);
            }else{
                System.out.println(srcFileName+"操作失败,mark值:"+mark);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //run调用lame解码器最后释放内存
            runTime.freeMemory();
        }
    }
    /**7.PCM转换为16K的PCM*/
    public static void changePcmTo16KPcm(String ar,String srcFileName,String rootPath,String targetFileName)throws Exception{
        Runtime runTime = null;
        try {
            runTime = Runtime.getRuntime();
            long start=System.currentTimeMillis();
            //在指定目录下执行cmd命令
            Process process=runTime.exec("cmd /c ffmpeg -y -f s16le -ar "+ar+" -ac 1 -i "+srcFileName+" -acodec pcm_s16le -f s16le -ac 1 -ar 16000 "+targetFileName,null,new File(rootPath));
            //释放进程
            process.getOutputStream().close();
            process.getInputStream().close();
            process.getErrorStream().close();
            int mark=process.waitFor();
            if(mark==0){
                long end=System.currentTimeMillis();
                System.out.println("转换成功, 耗时:"+(end-start)+"ms");
                System.out.println("路径保存在: "+rootPath);
            }else{
                System.out.println(srcFileName+"操作失败,mark值:"+mark);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //run调用lame解码器最后释放内存
            runTime.freeMemory();
        }
    }
    /**8.Wav转换为16K的Wav*/
    public static void changeWavTo16KWav(String srcFileName,String rootPath,String targetFileName)throws Exception{
        Runtime runTime = null;
        try {
            runTime = Runtime.getRuntime();
            long start=System.currentTimeMillis();
            //在指定目录下执行cmd命令
            Process process=runTime.exec("cmd /c ffmpeg -y -i "+srcFileName+" -acodec pcm_s16le -b 16000 -ac 1 -ar 16000 "+targetFileName,null,new File(rootPath));
            //释放进程
            process.getOutputStream().close();
            process.getInputStream().close();
            process.getErrorStream().close();
            int mark=process.waitFor();
            if(mark==0){
                long end=System.currentTimeMillis();
                System.out.println("转换成功, 耗时:"+(end-start)+"ms");
                System.out.println("路径保存在: "+rootPath);
            }else{
                System.out.println(srcFileName+"操作失败,mark值:"+mark);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //run调用lame解码器最后释放内存
            runTime.freeMemory();
        }
    }
    /**9.PCM转换为16K的Wav*/
    public static void change16KPcmTo16KWav(String srcFileName,String rootPath,String targetFileName)throws Exception{
        Runtime runTime = null;
        try {
            runTime = Runtime.getRuntime();
            long start=System.currentTimeMillis();
            //在指定目录下执行cmd命令
            Process process=runTime.exec("cmd /c ffmpeg -f s16le -ar 16000 -ac 1 -i "+srcFileName+" "+targetFileName,null,new File(rootPath));
            //释放进程
            process.getOutputStream().close();
            process.getInputStream().close();
            process.getErrorStream().close();
            int mark=process.waitFor();
            if(mark==0){
                long end=System.currentTimeMillis();
                System.out.println("转换成功, 耗时:"+(end-start)+"ms");
                System.out.println("路径保存在: "+rootPath);
            }else{
                System.out.println(srcFileName+"操作失败,mark值:"+mark);
            }
            long end=System.currentTimeMillis();
            System.out.println("转换成功, 耗时:"+(end-start)+"ms");
            System.out.println("路径保存在: "+rootPath);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //run调用lame解码器最后释放内存
            runTime.freeMemory();
        }
    }
    /**10.Mp4视频的切割*/
    public static void cutMp4(String startTime,String endTime,
                              String srcFileName,String rootPath,String targetFileName)throws Exception{
        Runtime runTime = null;
        try {
            runTime = Runtime.getRuntime();
            long start=System.currentTimeMillis();
            //在指定目录下执行cmd命令
            //ffmpeg -ss 00:00:00 -t 00:00:03 -i source.mp4 -vcodec copy -acodec copy myCut.mp4
            Process process=runTime.exec("cmd /c ffmpeg -ss " +startTime
                    +" -t "+endTime+" -i "
                    +srcFileName+" -vcodec copy -acodec copy "
                    +targetFileName,null,new File(rootPath));
            //释放进程
            process.getOutputStream().close();
            process.getInputStream().close();
            process.getErrorStream().close();
            int mark=process.waitFor();
            if(mark==0){
                long end=System.currentTimeMillis();
                System.out.println("分割成功, 耗时:"+(end-start)+"ms");
                System.out.println("路径保存在: "+rootPath);
            }else{
                System.out.println(srcFileName+"操作失败,mark值:"+mark);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //run调用lame解码器最后释放内存
            runTime.freeMemory();
        }
    }
    /**11.PCM音频的切割*/
    public static void cutPCM(String startTime,String endTime,
                              String srcFileName,String rootPath,String targetFileName)throws Exception{
        Runtime runTime = null;
        try {
            runTime = Runtime.getRuntime();
            long start=System.currentTimeMillis();
            //在指定目录下执行cmd命令
            //ffmpeg -f s16le -ar 16000 -acodec pcm_s16le -i source.pcm -ss 00:00:00 -t 00:00:03  -f s16le -ar 16000 -ac 1 myCut.pcm
            Process process=runTime.exec("cmd /c ffmpeg -f s16le -ar 16000 -acodec pcm_s16le -i "
                    +srcFileName
                    +" -ss "
                    +startTime
                    +" -t "+endTime+" -f s16le -ar 16000 -ac 1 "
                    +targetFileName,null,new File(rootPath));
            //释放进程
            process.getOutputStream().close();
            process.getInputStream().close();
            process.getErrorStream().close();
            int mark=process.waitFor();
            if(mark==0){
                long end=System.currentTimeMillis();
                System.out.println("分割成功, 耗时:"+(end-start)+"ms");
                System.out.println("路径保存在: "+rootPath);
            }else{
                System.out.println(srcFileName+"操作失败,mark值:"+mark);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //run调用lame解码器最后释放内存
            runTime.freeMemory();
        }
    }
}

2、把FLV转成MP3

ffmpeg -i 1.flv -b:a 320k -f MP3 1.mp3 #FLV转成MP3 

Java中使用FFmpeg实现视频的拆分和合并,通常需要借助FFmpeg的命令行工具,并通过Java的ProcessBuilder类来执行这些命令。以下是一个简单的Java工具类示例,展示了如何使用FFmpeg命令进行视频的拆分和合并: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class VideoUtil { // 执行FFmpeg命令并获取输出 public static String executeCommand(String... cmd) throws IOException { ProcessBuilder processBuilder = new ProcessBuilder(cmd); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder output = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { output.append(line).append("\n"); } int exitCode = process.waitFor(); if (exitCode != 0) { throw new RuntimeException("Command execution failed with exit code " + exitCode + ":\n" + output); } return output.toString(); } // 拆分视频 public static void splitVideo(String inputPath, String outputPath, int startTime, int endTime) { String[] cmd = { "ffmpeg", "-i", inputPath, "-ss", String.valueOf(startTime), "-to", String.valueOf(endTime), "-c", "copy", outputPath }; try { String result = executeCommand(cmd); System.out.println("Video split result: " + result); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } // 合并视频 public static void mergeVideo(String[] inputFiles, String outputFilePath) { StringBuilder cmd = new StringBuilder("ffmpeg -f concat -safe 0 -i "); for (int i = 0; i < inputFiles.length; i++) { cmd.append(" -i ").append(inputFiles[i]); } cmd.append(" -c copy ").append(outputFilePath); String[] cmdArray = cmd.toString().split(" "); try { String result = executeCommand(cmdArray); System.out.println("Video merge result: " + result); } catch (IOException e) { e.printStackTrace(); } } } ``` 使用方法: - 调用`splitVideo`方法来拆分视频,指定输入视频路径、输出视频路径以及拆分的开始时间和结束时间。 - 调用`mergeVideo`方法来合并视频,传入一个包含所有要合并视频文件路径的字符串数组,以及最终输出的视频路径。 示例使用代码: ```java public class Main { public static void main(String[] args) { // 拆分视频示例 VideoUtil.splitVideo("input.mp4", "output.mp4", 0, 10); // 合并视频示例 String[] videoFiles = {"video1.mp4", "video2.mp4"}; VideoUtil.mergeVideo(videoFiles, "mergedVideo.mp4"); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值