使用ffmpeg进行音频采样率转换

最近有需求要对一部分语音进行识别分析语音内容,供应商提供的接口对采样率有要求,指定8k或16k采样率,我们的语音采样率各不相同,所以需要一个工具进行统一的采样率转换。使用的是ffmpeg程序进行转换。
demo如下

package com.rui.demo.rateexchange;

import java.io.*;

import static com.sun.media.jfxmediaimpl.HostUtils.isLinux;

public class RateExchange {
    // FFmpeg全路径
    private static final String FFMPEG_PATH_WIN = "C:\\Users\\user\\Desktop\\ffmpeg-amd64.exe";

    private static final String FFMPEG_PATH_LINUX = "/usr/local/soft/ffmpeg-amd64";

    private static String ffmpegPath() {
        if (isLinux()) {
            return FFMPEG_PATH_LINUX;
        }
        return FFMPEG_PATH_WIN;
    }

    public static void mp3toMav(String audioInputPath, String audioOutPath, int rate) {
        String command = ffmpegPath() + " -i " + audioInputPath + "  -ar " + rate + " " + audioOutPath;
        processRun(command);
    }


    private static void processRun(String command) {
        Process process = null;
        InputStream errorStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader br = null;
        try {
            process = Runtime.getRuntime().exec(command);
            errorStream = process.getErrorStream();
            inputStreamReader = new InputStreamReader(errorStream);
            br = new BufferedReader(inputStreamReader);
            // 用来收集错误信息的
            String str = "";
            while ((str = br.readLine()) != null) {
                System.out.println(str);
            }
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (errorStream != null) {
                    errorStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        //需要转换的采样率
        int rate = 8000;
        //需要转换的原文件夹地址
        String inputPath = "E:\\mp3源文件\\";
        //转换后输出的目标文件夹地址
        String outputPath = "E:\\mp3-8k\\";
        File inputFileDirectory = new File(inputPath);
        File[] fileList = inputFileDirectory.listFiles();
        for (File file : fileList) {
            if (!file.isDirectory()) {
//                System.out.println(file.getName());
                mp3toMav(file.getAbsolutePath(), outputPath + file.getName() + ".wav", rate);
            }
        }
    }
}

你可能感兴趣的:(java,ffmpeg,音视频,java)