準(zhǔn)備環(huán)境:
springboot2.x
maven
1.第一步宿接,在pom.xml文件中加入JavaCV依賴,如下:
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>1.5.4</version>
</dependency>
2.編寫如下函數(shù):
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());
//如果為空业舍,會(huì)觸發(fā)自動(dòng)檢索音頻編碼
/*設(shè)置下面三個(gè)參數(shù)會(huì)觸發(fā)ffmpeg的swresample音頻重采樣*/
//在對(duì)音頻編碼解碼成pcm之后赎懦,如果sampleFormat與pcm不同,則會(huì)對(duì)音頻采樣格式進(jìn)行轉(zhuǎn)換
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.調(diào)用轉(zhuǎn)換函數(shù)巫延,如下:
void contextLoads() {
String inputPath="C:\\AAA\\BBB\\test1.webm";
String outputPath="C:\\AAA\\BBB\\test1.pcm";
convertToPCM(inputPath, outputPCMPath);
}
4.最后會(huì)在路徑C:\AAA\BBB\ 下生成文件test1.pcm