Chinaunix首页 | 论坛 | 博客
  • 博客访问: 544723
  • 博文数量: 298
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 3077
  • 用 户 组: 普通用户
  • 注册时间: 2019-06-17 10:57
文章分类

全部博文(298)

文章存档

2022年(96)

2021年(201)

2019年(1)

我的朋友

分类: Java

2021-04-20 12:44:53

本功能实现需要用到第三方jar包 jave,JAVE 是java调用FFmpeg的封装工具。

spring boot项目pom文件中添加以下依赖

    
     
		
			ws.schild
			jave-nativebin-win64
			3.1.1
		
     
		
			ws.schild
			jave-nativebin-linux64
			3.1.1
		

Java单类实现代码,复制到Spring boot项目中

import ws.schild.jave.Encoder;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;
 
import java.io.File;
import java.util.Arrays;
 
 //java项目www fhadmin org
public class VideoToAudio {
 
 
    //要输出的音频格式
    private static String outputFormat="mp3";
 
 
    /**
     * 获得转化后的文件名
     * @param sourceFilePath : 源视频文件路径
     * @return
     */
    public static String  getNewFileName(String sourceFilePath) {
        File source = new File(sourceFilePath);
        String fileName=source.getName().substring(0, source.getName().lastIndexOf("."));
        return fileName+"."+outputFormat;
    }
 
    /**
     * 转化音频格式
     * @param sourceFilePath : 源视频文件路径
     * @param targetFilePath : 目标音乐文件路径
     * @return
     */
    public static void transform(String sourceFilePath, String targetFilePath) {
        File source = new File(sourceFilePath);
        File target = new File(targetFilePath);
        // 设置音频属性
        AudioAttributes audio = new AudioAttributes();
        audio.setCodec(null);
        // 设置转码属性
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setOutputFormat(outputFormat);
        attrs.setAudioAttributes(audio);
        try {
            // 音频转换格式类
            Encoder encoder = new Encoder();
            MultimediaObject mediaObject=new MultimediaObject(source);
            encoder.encode(mediaObject, target, attrs);
            System.out.println("转换已完成...");
        }  catch (EncoderException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 批量转化音频格式
     * @param sourceFolderPath : 源视频文件夹路径
     * @param targetFolderPath : 目标音乐文件夹路径
     * @return
     */
    public static void batchTransform(String sourceFolderPath, String targetFolderPath) {
        File sourceFolder = new File(sourceFolderPath);
        if(sourceFolder.list().length!=0){
            Arrays.asList(sourceFolder.list()).forEach(e->{
              transform(sourceFolderPath+"\\"+e, targetFolderPath+"\\"+getNewFileName(e));
            });
        }
    }
 
 
 
    public static void main(String[] args) {
        batchTransform("C:\\Users\\tarzan\\Desktop\\video","C:\\Users\\tarzan\\Desktop\\audio");
    }
 
 
 
 
}

运行结果截图

 

阅读(2010) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~