JavaCV教程篇2之springboot调用ffmpeg从webm视频中提取出pcm音频文件

准备环境:
springboot2.x
maven
1.第一步,在pom.xml文件中加入JavaCV依赖,如下:


            org.bytedeco
            javacv-platform
            1.5.4
 

2.编写如下函数:

import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.timeout.IdleStateEvent;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.ffmpeg.global.avcodec;
import java.io.*;
import java.nio.ShortBuffer;

   public static void convertToPCM(String inputPath, String outputPath) throws IOException {
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputPath);
        grabber.setAudioCodecName(grabber.getAudioCodecName());
        //如果为空,会触发自动检索音频编码
        /*设置下面三个参数会触发ffmpeg的swresample音频重采样*/
        //在对音频编码解码成pcm之后,如果sampleFormat与pcm不同,则会对音频采样格式进行转换
        grabber.setSampleFormat(avutil.AV_SAMPLE_FMT_S16);
        //音频采样格式,使用avutil中的像素格式常量,例如:avutil.AV_SAMPLE_FMT_NONE
        //AV_SAMPLE_FMT_S16
        grabber.setAudioChannels(1);
        grabber.setSampleRate(16000);
        grabber.start();
        Frame captured_frame = null;
        FileOutputStream fos = new FileOutputStream(outputPath, true);
        DataOutputStream dos = new DataOutputStream(fos);
        while ((captured_frame = grabber.grabFrame()) != null) {
            try {
                System.out.println(captured_frame.samples);
                if (captured_frame.samples != null) {
                    ShortBuffer shortBuffer = (ShortBuffer) captured_frame.samples[0];
                    if (shortBuffer != null) {
                        while (shortBuffer.hasRemaining()) {
                            dos.writeShort(shortBuffer.get());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        grabber.stop();
        dos.close();
    }

3.调用转换函数,如下:

 void contextLoads() {
        String inputPath="C:\\AAA\\BBB\\test1.webm";
        String outputPath="C:\\AAA\\BBB\\test1.pcm";
       convertToPCM(inputPath, outputPCMPath);
    }

4.最后会在路径C:\AAA\BBB\ 下生成文件test1.pcm

你可能感兴趣的:(JavaCV教程篇2之springboot调用ffmpeg从webm视频中提取出pcm音频文件)