FFmpeg 是一个开源免费跨平台的视频和音频流方案,属于自由软件,采用 LGPL 或GPL 许可证(依据你选择的组件)

FFmpeg 官网:

FFMPEG分为3个版本:Static,Shared,Dev。

前两个版本可以直接在命令行中使用,他们的区别在于:

Static里面只有3个应用程序:ffmpeg.exe,ffplay.exe,ffprobe.exe,每个exe的体积都很大,相关的Dll已经被编译到exe里面去了。

Shared里面除了3个应用程序:ffmpeg.exe,ffplay.exe,ffprobe.exe之外,还有一些Dll,比如说avcodec-54.dll之类的。Shared里面的exe体积很小,他们在运行的时候,到相应的Dll中调用功能。

1、直接使用命令行进行转换;

(前提:Windows提前安装FFMPEG并配置环境变量(把bin路径放到path中))注:cmd命令行窗口,输入命令“ffmpeg –version”。窗口返回ffmpeg的版本信息,说明安装成功。即可进行文件转换了。

①:FFmpeg的Windows包-编解码文档类资源-CSDN下载;②官网下载

  • 相关命令参数解释如下:
-- 通用选项
-L license
-h 帮助
-fromats 显示可用的格式,编解码的
-f fmt 强迫采用格式fmt
-I filename 输入文件
-y 覆盖输出文件
-t duration 设置纪录时间 hh:mm:ss[.xxx]格式的记录时间也支持
-ss position 搜索到指定的时间 [-]hh:mm:ss[.xxx]的格式也支持
-title string 设置标题
-author string 设置作者
-copyright string 设置版权
-comment string 设置评论
-target type 设置目标文件类型(vcd,svcd,dvd) 所有的格式选项(比特率,编解码以及缓冲区大小)自动设置,只需要输入如下的就可以了:
ffmpeg -i myfile.avi -target vcd /tmp/vcd.mpg
-hq 激活高质量设置
-itsoffset offset 设置以秒为基准的时间偏移,该选项影响所有后面的输入文件。该偏移被加到输入文件的时戳,定义一个正偏移意味着相应的流被延迟了 offset秒。 [-]hh:mm:ss[.xxx]的格式也支持

-- 音频选项
-ab bitrate 设置音频码率
-ar freq 设置音频采样率
-ac channels 设置通道 缺省为1
-an 不使能音频纪录
-acodec codec 使用codec编解码

-- 音频捕获选项
-vd device 设置视频捕获设备 
-vc channel 设置视频捕获通道 DV1394专用
-tvstd standard 设置电视标准 NTSC PAL(SECAM)
-dv1394 设置DV1394捕获
-av device 设置音频设备 

-- 高级选项
-map file:stream 设置输入流映射
-debug 打印特定调试信息
-benchmark 为基准测试加入时间
-hex 倾倒每一个输入包
-bitexact 仅使用位精确算法 用于编解码测试
-ps size 设置包大小,以bits为单位
-re 以本地帧频读数据,主要用于模拟捕获设备
-loop 循环输入流。只工作于图像流,用于ffserver测试

-- 具体示例
1.mp3转wav (默认格式):
ffmpeg -i XXX.mp3 -f wav XXX.wav

2.mp3转pcm (自定义格式:采样率16000hz,分辨率16bits,单声道):
ffmpeg -i xxx.mp3 -acodec pcm_s16le -f s16le -ac 1 -ar 16000 xxx.pcm

3.mp3转ogg
ffmpeg -i xxx.mp3 -acodec libvorbis -ab 128k xxx.ogg

4.amr转wav:
ffmpeg -acodec libamr_nb -i XXX.amr XXX.wav

5.amr转mp3:
ffmpeg -i XXX.amr XXX.mp3

6.wav转amr:
ffmpeg -i XXX.wav -acodec libamr_nb -ab 12.2k -ar 8000 -ac 1 XXX.amr

7.wav转mp3:
ffmpeg -i XXX.wav -f mp3 -acodec libmp3lame -y XXX.mp3

8.wav转pcm:
ffmpeg -i xxx.wav -acodec pcm_s16le -f s16le -ac 1 -ar 16000 xxx.pcm

9.m4a转wav (默认格式): 
ffmpeg -i XXX.m4a -f wav XXX.wav
for %i in (D:\test\mp3\*.m4a) do ffmpeg -i "%i" -acodec pcm_s16le -ac 2 -ar 44100 "%i.wav"

10.m4a转mp3 当使用libmp3lame时,-aq 参数映射到 LAME的 -V 参数 ,参数范围0-9,0代表最高质量,9代表最低质量。
ffmpeg -i 音乐.m4a -y -acodec libmp3lame -aq 0 音乐.mp3
批量转换
for %i in (D:\test\mp3\*.m4a) do ffmpeg -i "%i" -y -acodec libmp3lame -aq 0 "%i~out.mp3"
音乐.m4a.mp3 修改文件名,先删除.mp3,再删除.m4a,最后再添加.mp3,即可得到正确的文件名;音乐.mp3
ren *.mp3 *.& ren *.m4a *. &ren *. *.mp3
mp3转m4a
ffmpeg -i 音乐.mp3 -acodec alac -ab 128k -ar 48000 -ac 2 -y 音乐.m4a 

-acodec codec 使用codec编解码
wav====>pcm_s16le
mp3====>libmp3lame

使用批处理如下:例如out.cmd,双击执行即可!

echo off 
::指定起始文件夹
set DIR="D:\test\mp3\"
echo DIR=%DIR%
:: 参数 /R 表示需要遍历子文件夹,去掉表示不遍历子文件夹
:: %%f 是一个变量,类似于迭代器,但是这个变量只能由一个字母组成,前面带上%%
:: 括号中是通配符,可以指定后缀名,*.*表示所有文件
:: for /R %DIR% %%f in (*.m4a) do ( 
for /R %DIR% %%f in (*.m4a) do ( 
echo %%f
:: =========真正的转换命令=================
:: 转成wav
:: ffmpeg  -i  %%f %%f.wav
:: 转成mp3
ffmpeg -i %%f -y -acodec libmp3lame -aq 0  %%f.mp3
:: 删除原始文件
del %%f
)
:: 修改文件名 ren *.mp3 *.& ren *.m4a *. &ren *. *.mp3
ren %DIR%*.mp3 *.& ren %DIR%*.m4a *. &ren %DIR%*. *.mp3
pause

2、使用代码的方式

①导入相关包

<!--  音频转换 -->
        <dependency>
            <groupId>com.github.dadiyang</groupId>
            <artifactId>jave</artifactId>
            <version>1.0.5</version>
        </dependency>

        <!--  导入本地jar -->
        <!--  音频转换 本地下载 http://www.sauronsoftware.it/projects/jave/download.php -->
       <!-- JAVE(Java Audio Video Encoder),是一个包涵ffmpeg项目库。开发这可以运用它去实现音频(Audio)与视频(Video)文件的转码。例如你要把AVI格式文件转为MPEG文件、WAV格式文件转为MP3格式文件,同时你还能调整文件大小与比例。-->
        <!--<dependency>
            <groupId>com.well.dev</groupId>
            <artifactId>audio-pakge</artifactId>
            <version>1.0.2-SNAPSHOT</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/jar/jave-1.0.2.jar</systemPath>
        </dependency>-->

②具体工具类

import it.sauronsoftware.jave.*;
import lombok.extern.slf4j.Slf4j;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 音频转换工具类
 * ffmpeg-- https://ffmpeg.org/documentation.html
 *
 * @date 2022/07/25
 */
@Slf4j
public class AudioConvertUtils {
    /**
     * 根据远程资源路径,下载资源到本地临时目录
     *
     * @param remoteSourceUrl 远程资源路径
     * @param tmpFileFolder   本地临时目录
     * @return 下载后的文件物理路径
     */
    private static String downloadSource(String remoteSourceUrl, String tmpFileFolder) throws Exception {
        //下载资源
        URL url = new URL(remoteSourceUrl);
        DataInputStream dataInputStream = new DataInputStream(url.openStream());
        String tmpFilePath = tmpFileFolder + getOriginalFileName(remoteSourceUrl);
        FileOutputStream fileOutputStream = new FileOutputStream(new File(tmpFilePath));
        byte[] bytes = new byte[1024];
        int length = 0;
        while ((length = dataInputStream.read(bytes)) != -1) {
            fileOutputStream.write(bytes, 0, length);
            // System.out.println("下载中....");
        }
        // System.out.println("下载完成...");
        dataInputStream.close();
        fileOutputStream.close();
        return tmpFilePath;
    }

    /**
     * 根据路径获取文件夹下的所有文件路径
     */
    public static List<String> getFileUrl (String url, String path){
        File f = new File(path);
        if (!f.exists()) {
            System.out.println(path + " not exists");
            return new ArrayList<>();
        }
        File fa[] = f.listFiles();
        List<String> result = new ArrayList<>();
        for (int i = 0; i < fa.length; i++) {
            if (fa[i].isFile()) {
                File fs = fa[i];
                result.add(url + "/" + fs.getName());
            }
        }
        System.out.println("result = " + result);
        return result;
    }
    /**
     * 将本地音频文件转换成mp3格式文件
     *
     * @param localFilePath 本地音频文件物理路径
     * @param targetPath    转换后mp3文件的物理路径
     */
    public static void changeLocalSourceToMp3(String localFilePath, String targetPath) throws Exception {

        File source = new File(localFilePath);
        //source.get
        File target = new File(targetPath);
        //=============== 1-音频 ===========================
        AudioAttributes audio = new AudioAttributes();
        //设置编码器
        audio.setCodec("libmp3lame");
        // setBitRate(java.lang.Integer bitRate)//设置比特率
        // setSamplingRate(java.lang.Integer bitRate)//设置节录率
        // setChannels(java.lang.Integer channels)//设置声音频道
        // setVolume(java.lang.Integer volume)//设置音量

        //=============== 2-视频 ===========================
//        VideoAttributes video = new VideoAttributes();
//        video.setCodec("mpeg4");
//        video.setBitRate(new Integer(160000));
//        video.setFrameRate(new Integer(15));
//        video.setSize(new VideoSize(176, 144));

        //=============== 2-编码 ===========================
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setFormat("mp3");
        attrs.setAudioAttributes(audio);
        //attrs.setVideoAttributes(video);

        Encoder encoder = new Encoder();
        encoder.encode(source, target, attrs);
        System.out.println("文件转换成功 = ");
    }

    /**
     * 下载远程文件到本地,然后转换成mp3格式,并返回mp3的文件绝对路径
     * <p>
     * <p>
     * <p>
     * 每次会优先检测mp3文件是否已存在,存在则直接返回mp3绝对路径,否则下载然后转换成mp3再返回
     *
     * @param remoteSourceUrl 远程文件的URL
     * @param tmpFolder       临时文件存放的目录,如/usr/consult/tmp/
     * @return 转换成mp3的文件的绝对路径,如/usr/consult/tmp/fcd124a2-ed6c-4407-b574-81ecc51b4eb4.mp3
     */
    public static String changeRemoteSourceToMp3(String remoteSourceUrl, String tmpFolder) throws Exception {
        // 检测该文件是否已经下载并转换过一次,如果是,则直接返回
        String remoteSourceNameWithoutSuffix = getNameWithoutSuffix(remoteSourceUrl);
        // 格式为/usr/consult/tmp/fcd124a2-ed6c-4407-b574-81ecc51b4eb4.mp3
        String mp3FilePath = tmpFolder + File.separator + remoteSourceNameWithoutSuffix + ".mp3";
        File audioFile = new File(mp3FilePath);
        if (audioFile.exists()) {
            // 文件已在之前转换过一次,直接返回即可
            return mp3FilePath;
        }
        // 下载资源到临时目录
        String tmpRemoteFilePath = downloadSource(remoteSourceUrl, tmpFolder);
        // 转换成mp3格式
        changeLocalSourceToMp3(tmpRemoteFilePath, mp3FilePath);
        return mp3FilePath;

    }

    /**
     * 根据文件url获取文件名(包含后缀名)
     *
     * @param url 文件url
     * @return 文件名(包含后缀名)
     */
    private static String getOriginalFileName(String url) {
        String[] sarry = url.split("/");
        return sarry[sarry.length - 1];

    }

    /**
     * 根据文件url获取文件名(不包含后缀名)
     *
     * @param url 文件url
     * @return 文件名(包含后缀名)
     */
    private static String getNameWithoutSuffix(String url) {
        String originalFileName = getOriginalFileName(url);
        return originalFileName.substring(0, originalFileName.indexOf("."));

    }

    public static void main(String[] args) throws Exception {
        //String result = changeRemoteSourceToMp3("D:\\test", "D:\\test\\mp3");
        //System.out.println(result);
        changeLocalSourceToMp3("D:\\test\\人间烟火.m4a", "D:\\test\\mp3\\人间烟火.mp3");
        //transforMusicFormat("D:\\test\\人间烟火.m4a","D:\\test\\mp3\\人间烟火.mp3");
        conversionormat("小城夏天");

        getFileUrl("D:\\test\\","D:\\test");


    }


    /**
     * 转化音频格式
     *
     * @param oldFormatPath : 原音乐路径
     * @param newFormatPath : 目标音乐路径
     * @return
     */
    public static boolean transforMusicFormat(String oldFormatPath, String newFormatPath) {
        File source = new File(oldFormatPath);
        File target = new File(newFormatPath);
        //System.setProperty("ffmpeg.home", "D:\\tool\\ffmpeng\\bin");
        // 音频转换格式类
        Encoder encoder = new Encoder();

        // 设置音频属性
        AudioAttributes audio = new AudioAttributes();
        audio.setCodec(null);
        // 设置转码属性
        EncodingAttributes attrs = new EncodingAttributes();
        //attrs.setFormat("mp3");
        attrs.setFormat("wav");
        attrs.setAudioAttributes(audio);

        try {
            encoder.encode(source, target, attrs);
            System.out.println("attrs = " + attrs);
            //deleteFile(oldFormatPath);
            System.out.println("文件转换成功 = ");
            return true;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InputFormatException e) {
            e.printStackTrace();
        } catch (EncoderException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除原音频文件
     *
     * @param filePath : 原文件路径
     * @return
     */
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            // 文件删除
            file.delete();
            return true;
        }
        return false;
    }

    /**
     * 判断格式是否需要转换
     *
     * @param musicName
     * @return
     */
    public static boolean checkMusicFormat(String musicName) {
        if (musicName == null || "".equals(musicName)) {
            return false;
        }
        String suffix = musicName.substring(musicName.lastIndexOf(".") + 1);
        if ("mp3".equals(suffix) || "wav".equals(suffix)) {
            return false;
        }
        return true;
    }


    //根据文件名去转换
    public static String conversionormat(String fileName) {
        String webroot = "D:\\tool\\ffmpeng\\bin";  //ffmpeg安装路径

        String sourcePath = "D:\\test\\" + fileName + ".m4a";
        String targetPath = "D:\\test\\mp3\\" + fileName + ".wav";
        Runtime run = null;
        try {
            run = Runtime.getRuntime();
            long start = System.currentTimeMillis();
            System.out.println(new File(webroot).getAbsolutePath());

            //执行ffmpeg.exe,前面是ffmpeg.exe的地址,中间是需要转换的文件地址,后面是转换后的文件地址。-i是转换方式,意思是可编码解码,mp3编码方式采用的是libmp3lame
            Process p = run.exec(new File(webroot).getAbsolutePath() + "/ffmpeg -y -i " + sourcePath + " -acodec pcm_s16le -ac 2 -ar 8000 " + targetPath);
            p.getOutputStream().close();
            p.getInputStream().close();
            p.getErrorStream().close();
            p.waitFor();
            long end = System.currentTimeMillis();

            System.out.println(sourcePath + " convert success, costs:" + (end - start) + "ms");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            //run调用lame解码器最后释放内存
            run.freeMemory();
        }
        return "success!";
    }


}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐