利用ffmpeg库结合Java语言实现音频转换

发布于:2025-06-23 ⋅ 阅读:(14) ⋅ 点赞:(0)

mp4 to wav

public class AudioExtractor {
    public static void main(String[] args) {
        String videoPath = "/RVC/sky.mp4";  // mp4输入文件路径
        String audioPath = "/RVC/sky.wav"; // wav输出文件路径
        String outputPath = "/ans/ksm-island.mp3"; // MP3输出路径
//        String videoPath = "/asweare.mp4";  //
//        String audioPath = "/asweare.wav"; // 
        // 构建FFmpeg命令
        String command = String.format(
                "ffmpeg -i %s -vn -acodec pcm_s16le -ar 44100 -ac 2 %s",
                videoPath, audioPath
        );
        String command2 = String.format(
                "ffmpeg -i %s -vn -acodec libmp3lame -q:a 2 -ar 44100 -ac 2 %s",
                audioPath, outputPath
        );
        try {
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line); 
            }
            System.out.println("音频提取完成!");
            Process process2 = Runtime.getRuntime().exec(command2);
     
            BufferedReader errorReader = new BufferedReader(
                    new InputStreamReader(process2.getErrorStream())
            );
            String line2;
            while ((line2 = errorReader.readLine()) != null) {
                System.out.println(line2);
            }

            int exitCode = process2.waitFor();
            if (exitCode == 0) {
                System.out.println("转换成功!输出文件: " + outputPath);
            } else {
                System.out.println("转换失败,错误码: " + exitCode);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

音频合并

public class AudioMerger {

    public static void main(String[] args) {
        String audio1 = "/instrument_sky.wav_10.wav";
        String audio2 = "/vocal_ksm_sky.wav";
        String output = "/ksm-sky-all.mp3";

        try {
            mergeAudioTracks(audio1, audio2, output);
            System.out.println("✅ 音频合并完成: " + output);
        } catch (Exception e) {
            System.err.println("❌ 合并失败: " + e.getMessage());
        }
    }

    /**
     * 合并两个音频文件(音轨叠加)
     * @param input1 第一个音频路径
     * @param input2 第二个音频路径
     * @param output 输出文件路径
     */
    public static void mergeAudioTracks(String input1, String input2, String output)
            throws IOException, InterruptedException {
        List<String> command = new ArrayList<>(Arrays.asList(
                "ffmpeg",
                "-i", input1,
                "-i", input2,
                "-filter_complex", "[0:a][1:a]amerge=inputs=2[aout]", // 混合两个音轨
                "-map", "[aout]",
                "-ac", "2",          // 输出立体声
                "-b:a", "192k",      // 设置比特率
                "-y",                // 覆盖输出文件
                output
        ));
        
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectErrorStream(true); 

        Process process = builder.start();
        
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("[FFmpeg] " + line);
            }
        }
        
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new IOException("FFmpeg异常终止,退出码: " + exitCode);
        }
    }
}

截取mp4

public class FFmpegVideoClipper {

    public static void main(String[] args) {
        String inputVideo = "/LMH/LK1.mp4";
        String outputVideo = "/LMH/LK1-cut.mp4";
        int clipDuration = 1800; //单位s

        try {
            clipVideo(inputVideo, outputVideo, clipDuration);
            System.out.println("视频截取成功!");
        } catch (IOException | InterruptedException e) {
            System.err.println("视频处理失败: " + e.getMessage());
        }
    }

    /**
     * 使用FFmpeg截取视频前N秒
     * @param inputFile  输入视频路径
     * @param outputFile 输出视频路径
     * @param seconds    要截取的秒数
     */
    public static void clipVideo(String inputFile, String outputFile, int seconds)
            throws IOException, InterruptedException {
        
        ProcessBuilder processBuilder = new ProcessBuilder(
                "ffmpeg",
                "-i", inputFile,
                "-t", String.valueOf(seconds),
                "-c", "copy",  
                outputFile
        );
        
        Process process = processBuilder.start();
        int exitCode = process.waitFor();

        if (exitCode != 0) {
            throw new IOException("FFmpeg执行失败,退出码: " + exitCode);
        }
    }
}

wav to mp3

public class WavToMp3 {
    public static void main(String[] args) {
        String inputPath = "/ksm-island.wav";  // WAV输入路径
        String outputPath = "/ksm-island.mp3"; // MP3输出路径

        // FFmpeg命令参数说明:
        // -i 输入文件 | -vn 禁用视频 | -acodec libmp3lame 指定MP3编码器
        // -q:a 2 设置VBR质量(范围0-9,2=192kbps左右) | -ar 44100 采样率 | -ac 2 立体声
        String command = String.format(
                "ffmpeg -i %s -vn -acodec libmp3lame -q:a 2 -ar 44100 -ac 2 %s",
                inputPath, outputPath
        );

        try {
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader errorReader = new BufferedReader(
                    new InputStreamReader(process.getErrorStream())
            );
            String line;
            while ((line = errorReader.readLine()) != null) {
                System.out.println(line);
            }

            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("转换成功!输出文件: " + outputPath);
            } else {
                System.out.println("转换失败,错误码: " + exitCode);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到