1、首先需要下载FFmpeg;

2、Gradle依赖

  1. def void forceVersion(details, group, version) {
  2. if (details.requested.group == group) {
  3. details.useVersion version
  4. }
  5. }
  6.  
  7. def void forceVersion(details, group, name, version) {
  8. if (details.requested.group == group && details.requested.name == name) {
  9. details.useVersion version
  10. }
  11. }
  12.  
  13. allprojects { p ->
  14. group = 'com.my.spider'
  15. version = '1.0.0'
  16.  
  17. apply plugin: 'java'
  18. apply plugin: 'maven'
  19. apply plugin: 'maven-publish'
  20.  
  21. [compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
  22.  
  23. jar.doFirst {
  24. manifest {
  25. def manifestFile = "${projectDir}/META-INF/MANIFEST.MF"
  26. if (new File(manifestFile).exists())
  27. from (manifestFile)
  28.  
  29. attributes 'Implementation-Title':p.name
  30. if (p.version.endsWith('-SNAPSHOT')) {
  31. attributes 'Implementation-Version': p.version + '-' + p.ext.Timestamp
  32. } else {
  33. attributes 'Implementation-Version': p.version
  34. }
  35. attributes 'Implementation-BuildDateTime':new Date()
  36. }
  37. }
  38.  
  39. javadoc {
  40. options {
  41. encoding 'UTF-8'
  42. charSet 'UTF-8'
  43. author false
  44. version true
  45. links 'http://docs.oracle.com/javase/8/docs/api/index.html'
  46. memberLevel = org.gradle.external.javadoc.JavadocMemberLevel.PRIVATE
  47. }
  48. }
  49.  
  50. if (System.env.uploadArchives) {
  51. build.dependsOn publish
  52. }
  53.  
  54. buildscript {
  55. repositories {
  56. mavenCentral()
  57. }
  58. dependencies {classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.5.14.RELEASE' }
  59. }
  60.  
  61. afterEvaluate {Project project ->
  62. if (project.pluginManager.hasPlugin('java')) {
  63. configurations.all {
  64. resolutionStrategy.eachDependency {DependencyResolveDetails details ->
  65. forceVersion details, 'org.springframework.boot', '1.4.1.RELEASE'
  66. forceVersion details, 'org.slf4j', '1.7.21'
  67. forceVersion details, 'org.springframework', '4.3.3.RELEASE'
  68. }
  69.  
  70. exclude module:'slf4j-log4j12'
  71. exclude module:'log4j'
  72. }
  73.  
  74. dependencies {testCompile 'junit:junit:4.12' }
  75. }
  76. }
  77.  
  78. repositories {
  79. mavenCentral()
  80. }
  81.  
  82. // 时间戳:年月日时分
  83. p.ext.Timestamp = new Date().format('yyyyMMddHHmm')
  84. // Build Number
  85. p.ext.BuildNumber = System.env.BUILD_NUMBER
  86. if (p.ext.BuildNumber == null || "" == p.ext.BuildNumber) {
  87. p.ext.BuildNumber = 'x'
  88. }
  89. }
  90.  
  91. task zipSources(type: Zip) {
  92. description '压缩源代码'
  93. project.ext.zipSourcesFile = project.name + '-' + project.version + '-' + project.ext.Timestamp + '.' + project.ext.BuildNumber + '-sources.zip'
  94. archiveName = project.ext.zipSourcesFile
  95. includeEmptyDirs = false
  96.  
  97. from project.projectDir
  98.  
  99. exclude '**/.*'
  100. exclude 'build/*'
  101. allprojects.each { p ->
  102. exclude '**/' + p.name + '/bin/*'
  103. exclude '**/' + p.name + '/build/*'
  104. exclude '**/' + p.name + '/data/*'
  105. exclude '**/' + p.name + '/work/*'
  106. exclude '**/' + p.name + '/logs/*'
  107. }
  108. }
  109.  
  110. def CopySpec appCopySpec(Project prj, dstname = null) {
  111. if (!dstname) { dstname = prj.name }
  112. return copySpec{
  113. // Fat jar
  114. from (prj.buildDir.toString() + '/libs/' + prj.name + '-' + project.version + '.jar') {
  115. into dstname
  116. }
  117.  
  118. // Configs
  119. from (prj.projectDir.toString() + '/config/examples') {
  120. into dstname + '/config'
  121. }
  122.  
  123. // Windows start script
  124. from (prj.projectDir.toString() + '/' + prj.name + '.bat') {
  125. into dstname
  126. }
  127.  
  128. // Unix conf script
  129. from (prj.projectDir.toString() + '/' + prj.name + '.conf') {
  130. into dstname
  131. rename prj.name, prj.name + '-' + project.version
  132. }
  133. }
  134. }
  135.  
  136. task zipSetup(type: Zip, dependsOn: subprojects.build) {
  137. description '制作安装包'
  138. project.ext.zipSetupFile = project.name + '-' + project.version + '-' + project.ext.Timestamp + '.' + project.ext.BuildNumber + '-setup.zip'
  139. archiveName = project.name + '-' + project.version + '-' + project.ext.Timestamp + '.' + project.ext.BuildNumber + '-setup.zip'
  140.  
  141. with appCopySpec(project(':spider-demo'))
  142. }
  143.  
  144. import java.security.MessageDigest
  145.  
  146. def generateMD5(final file) {
  147. MessageDigest digest = MessageDigest.getInstance("MD5")
  148. file.withInputStream(){is->
  149. byte[] buffer = new byte[8192]
  150. int read = 0
  151. while( (read = is.read(buffer)) > 0) {
  152. digest.update(buffer, 0, read);
  153. }
  154. }
  155. byte[] md5sum = digest.digest()
  156. BigInteger bigInt = new BigInteger(1, md5sum)
  157. return bigInt.toString(16)
  158. }
  159.  
  160. task md5(dependsOn: [zipSetup, zipSources]) << {
  161. String md5_setup = generateMD5(file("${projectDir}/build/distributions/" + project.ext.zipSetupFile));
  162. String md5_sources = generateMD5(file("${projectDir}/build/distributions/" + project.ext.zipSourcesFile));
  163. println project.ext.zipSetupFile + '=' + md5_setup
  164. println project.ext.zipSourcesFile + '=' + md5_sources
  165.  
  166. def newFile = new File("${projectDir}/build/distributions/"
  167. + project.name + '-' + project.version + '-' + project.ext.Timestamp + '.' + project.ext.BuildNumber + '-md5.txt')
  168. PrintWriter printWriter = newFile.newPrintWriter()
  169. printWriter.println project.ext.zipSetupFile + '=' + md5_setup
  170. printWriter.println project.ext.zipSourcesFile + '=' + md5_sources
  171. printWriter.flush()
  172. printWriter.close()
  173. }
  174.  
  175. build.dependsOn subprojects.build, zipSetup, zipSources, md5

bulid.gradle

工程组件gradle依赖: 语音识别使用 百度api;需引入 compile 'com.baidu.aip:java-sdk:3.2.1'

  1. apply plugin: 'spring-boot'
  2. apply plugin: 'application'
  3.  
  4. distributions {
  5. main {
  6. contents {
  7. from ("${projectDir}/config/examples") {
  8. into "config"
  9. }
  10. }
  11. }
  12. }
  13.  
  14. distTar.enabled = false
  15.  
  16. springBoot {
  17. executable = true
  18. mainClass = 'com.my.ai.Application'
  19. }
  20.  
  21. dependencies {
  22. compile 'org.springframework.boot:spring-boot-starter-web:1.4.0.RELEASE'
  23. compile 'dom4j:dom4j:1.6.1'
  24. compile 'commons-httpclient:commons-httpclient:3.1'
  25. compileOnly 'com.h2database:h2:1.4.191'
  26. compile 'javax.cache:cache-api:1.0.0'
  27. compile 'org.jboss.resteasy:resteasy-jaxrs:3.0.14.Final'
  28. compile 'org.jboss.resteasy:resteasy-client:3.0.14.Final'
  29. // Axis
  30. compile 'axis:axis:1.4'
  31.  
  32. compile 'org.jsoup:jsoup:1.10.1'
  33.  
  34. compile 'com.alibaba:fastjson:1.2.21'
  35.  
  36. compile 'com.baidu.aip:java-sdk:3.2.1'
  37.  
  38. }

3、视频抽取音频服务“

  1. package com.my.ai.service;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.InputStreamReader;
  6. import java.util.List;
  7.  
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.stereotype.Service;
  11.  
  12. //视频抽取音频
  13. @Service
  14. public class ExtractAudioService {
  15.  
  16. public static Logger logger = LoggerFactory.getLogger(ExtractAudioService.class);
  17.  
  18. public static void main(String[] args) {
  19. new ExtractAudioService().getAudioFromVideo("E:\\QLDownload\\氧化还原反应中电子转移的方向和数目的表示方法\\氧化还原反应中电子转移的方向和数目的表示方法.mp4",
  20. "D:\\ffmpeg4.2\\bin\\ffmpeg.exe");
  21. }
  22.  
  23. public String getAudioFromVideo(String videoPath,String ffmpegPath) {
  24. File video = new File(videoPath);
  25. if(video.exists() && video.isFile()){
  26. String format = "wav";
  27. String outPath = videoPath.substring(0,videoPath.lastIndexOf(".")) + ".wav";
  28. processCmd(videoPath, ffmpegPath, format, outPath);
  29. return outPath;
  30. }
  31. return null;
  32. }
  33.  
  34. //D:\ffmpeg4.2\bin\ffmpeg.exe -i 氧化还原反应中电子转移的方向和数目的表示方法.mp4 -f wav -vn -y 3.wav
  35. public String processCmd(String inputPath,String ffmpegPath,String format,String outPath) {
  36. List<String> commend = new java.util.ArrayList<String>();
  37. commend.add(ffmpegPath);
  38. commend.add("-i");
  39. commend.add(inputPath);
  40. commend.add("-y");
  41. commend.add("-vn");
  42. commend.add("-f");
  43. commend.add(format);
  44. commend.add(outPath);
  45. try {
  46.  
  47. ProcessBuilder builder = new ProcessBuilder();
  48. builder.command(commend);
  49. builder.redirectErrorStream(true);
  50. Process p = builder.start();
  51.  
  52. // 1. start
  53. BufferedReader buf = null; // 保存ffmpeg的输出结果流
  54. String line = null;
  55. // read the standard output
  56.  
  57. buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
  58.  
  59. StringBuffer sb = new StringBuffer();
  60. while ((line = buf.readLine()) != null) {
  61. System.out.println(line);
  62. sb.append(line);
  63. continue;
  64. }
  65. p.waitFor();// 这里线程阻塞,将等待外部转换进程运行成功运行结束后,才往下执行
  66. // 1. end
  67. return sb.toString();
  68. } catch (Exception e) {
  69. // System.out.println(e);
  70. return null;
  71. }
  72. }
  73.  
  74. }

ExtractAudioService

4、音频切段:

  1. package com.my.ai.service;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.InputStreamReader;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import java.util.regex.Matcher;
  9. import java.util.regex.Pattern;
  10.  
  11. import org.slf4j.Logger;
  12. import org.slf4j.LoggerFactory;
  13. import org.springframework.stereotype.Service;
  14.  
  15. @Service
  16. public class CutService {
  17.  
  18. public static Logger logger = LoggerFactory.getLogger(CutService.class);
  19.  
  20. public List<String> cutFile(String media_path, String ffmpeg_path) {
  21.  
  22. List<String> audios = new ArrayList<>();
  23. int mediaTime = getMediaTime(media_path, ffmpeg_path);
  24. int num = mediaTime / 59;
  25. int lastNum = mediaTime % 59;
  26. System.out.println(mediaTime +"|" + num + "|"+ lastNum);
  27. int length = 59;
  28. File file = new File(media_path);
  29. String filename = file.getName();
  30. for (int i = 0; i < num; i++) {
  31. String outputPath = file.getParent() + File.separator + i + "-"+filename;
  32. processCmd(media_path, ffmpeg_path, String.valueOf(length * i) ,
  33. String.valueOf(length), outputPath);
  34. audios.add(outputPath);
  35. }
  36. if(lastNum > 0) {
  37. String outputPath = file.getParent() + File.separator + num + "-"+filename;
  38. processCmd(media_path, ffmpeg_path, String.valueOf(length * num) ,
  39. String.valueOf(lastNum), outputPath);
  40. audios.add(outputPath);
  41. }
  42. return audios;
  43. }
  44.  
  45. /**
  46. * 获取视频总时间
  47. *
  48. * @param viedo_path 视频路径
  49. * @param ffmpeg_path ffmpeg路径
  50. * @return
  51. */
  52. public int getMediaTime(String video_path, String ffmpeg_path) {
  53. List<String> commands = new java.util.ArrayList<String>();
  54. commands.add(ffmpeg_path);
  55. commands.add("-i");
  56. commands.add(video_path);
  57. try {
  58. ProcessBuilder builder = new ProcessBuilder();
  59. builder.command(commands);
  60. final Process p = builder.start();
  61.  
  62. // 从输入流中读取视频信息
  63. BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
  64. StringBuffer sb = new StringBuffer();
  65. String line = "";
  66. while ((line = br.readLine()) != null) {
  67. sb.append(line);
  68. }
  69. System.out.println(sb.toString());
  70. br.close();
  71.  
  72. // 从视频信息中解析时长
  73. String regexDuration = "Duration: (.*?), bitrate: (\\d*) kb\\/s";
  74. Pattern pattern = Pattern.compile(regexDuration);
  75. Matcher m = pattern.matcher(sb.toString());
  76. if (m.find()) {
  77. int time = getTimelen(m.group(1));
  78. System.out
  79. .println(video_path + ",视频时长:" + time + ",比特率:" + m.group(2) + "kb/s");
  80. return time;
  81. }
  82. } catch (Exception e) {
  83. e.printStackTrace();
  84. }
  85. return 0;
  86. }
  87.  
  88. // 格式:"00:00:10.68"
  89. public int getTimelen(String timelen) {
  90. int min = 0;
  91. String strs[] = timelen.split(":");
  92. if (strs[0].compareTo("0") > 0) {
  93. min += Integer.valueOf(strs[0]) * 60 * 60;// 秒
  94. }
  95. if (strs[1].compareTo("0") > 0) {
  96. min += Integer.valueOf(strs[1]) * 60;
  97. }
  98. if (strs[2].compareTo("0") > 0) {
  99. min += Math.round(Float.valueOf(strs[2]));
  100. }
  101. return min;
  102. }
  103.  
  104. //D:\ffmpeg4.2\bin\ffmpeg.exe -i 123.pcm -ss 0 -t 59 1-123.wav
  105. public String processCmd(String inputPath,String ffmpegPath,
  106. String startTime,String length,String outputPath) {
  107. List<String> commend = new java.util.ArrayList<String>();
  108. commend.add(ffmpegPath);
  109. commend.add("-i");
  110. commend.add(inputPath);
  111. commend.add("-ss");
  112. commend.add(startTime);
  113. commend.add("-t");
  114. commend.add(length);
  115. commend.add(outputPath);
  116. try {
  117.  
  118. ProcessBuilder builder = new ProcessBuilder();
  119. builder.command(commend);
  120. builder.redirectErrorStream(true);
  121. Process p = builder.start();
  122.  
  123. // 1. start
  124. BufferedReader buf = null; // 保存ffmpeg的输出结果流
  125. String line = null;
  126. // read the standard output
  127.  
  128. buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
  129.  
  130. StringBuffer sb = new StringBuffer();
  131. while ((line = buf.readLine()) != null) {
  132. System.out.println(line);
  133. sb.append(line);
  134. continue;
  135. }
  136. p.waitFor();// 这里线程阻塞,将等待外部转换进程运行成功运行结束后,才往下执行
  137. // 1. end
  138. return sb.toString();
  139. } catch (Exception e) {
  140. System.out.println(e);
  141. return null;
  142. }
  143. }
  144.  
  145. //ffmpeg -y -i 16k.wav -acodec pcm_s16le -f s16le -ac 1 -ar 16000 16k.pcm
  146. public static String processWavToPcm(String inputPath,String ffmpegPath,String outputPath) {
  147. List<String> commend = new java.util.ArrayList<String>();
  148. commend.add(ffmpegPath);
  149. commend.add("-i");
  150. commend.add(inputPath);
  151. commend.add("-acodec");
  152. commend.add("pcm_s16le");
  153. commend.add("-f");
  154. commend.add("s16le");
  155. commend.add("-ac");
  156. commend.add("1");
  157. commend.add("-ar");
  158. commend.add("16000");
  159. commend.add(outputPath);
  160. try {
  161.  
  162. ProcessBuilder builder = new ProcessBuilder();
  163. builder.command(commend);
  164. builder.redirectErrorStream(true);
  165. Process p = builder.start();
  166.  
  167. // 1. start
  168. BufferedReader buf = null; // 保存ffmpeg的输出结果流
  169. String line = null;
  170. // read the standard output
  171.  
  172. buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
  173.  
  174. StringBuffer sb = new StringBuffer();
  175. while ((line = buf.readLine()) != null) {
  176. System.out.println(line);
  177. sb.append(line);
  178. continue;
  179. }
  180. p.waitFor();// 这里线程阻塞,将等待外部转换进程运行成功运行结束后,才往下执行
  181. // 1. end
  182. return outputPath;
  183. //sb.toString();
  184. } catch (Exception e) {
  185. System.out.println(e);
  186. return null;
  187. }
  188. }
  189.  
  190. public static void main(String[] args) {
  191. List<String> audios = new CutService().cutFile(
  192. "E:\\QLDownload\\氧化还原反应中电子转移的方向和数目的表示方法\\氧化还原反应中电子转移的方向和数目的表示方法.wav",
  193. "D:\\ffmpeg4.2\\bin\\ffmpeg.exe");
  194. System.out.println(audios.size());
  195.  
  196. for (String wavPath : audios) {
  197. String out = wavPath.substring(0,wavPath.lastIndexOf(".")) + ".pcm";
  198. processWavToPcm(wavPath, "D:\\ffmpeg4.2\\bin\\ffmpeg.exe", out);
  199. }
  200.  
  201. }
  202.  
  203. }

5、音频格式转换,便于进行语音识别,代码如上:

6、调用sdk,获取识别结果:

  1. package com.my.ai.service;
  2.  
  3. import org.json.JSONObject;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.stereotype.Service;
  7.  
  8. import com.baidu.aip.speech.AipSpeech;
  9.  
  10. @Service
  11. public class TokenService {
  12.  
  13. public static Logger logger = LoggerFactory.getLogger(TokenService.class);
  14.  
  15. //设置APPID/AK/SK
  16. public static final String APP_ID = "***";
  17. public static final String API_KEY = "***";
  18. public static final String SECRET_KEY = "***";
  19. static AipSpeech client = null;
  20. static {
  21. if(client == null) {
  22. client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
  23. }
  24. }
  25.  
  26. public static void main(String[] args) {
  27. getResult("E:\\QLDownload\\氧化还原反应中电子转移的方向和数目的表示方法\\0-氧化还原反应中电子转移的方向和数目的表示方法.pcm");
  28. }
  29.  
  30. public static String getResult(String file) {
  31.  
  32. // 可选:设置网络连接参数
  33. client.setConnectionTimeoutInMillis(2000);
  34. client.setSocketTimeoutInMillis(60000);
  35. // 可选:设置代理服务器地址, http和socket二选一,或者均不设置
  36. //client.setHttpProxy("proxy_host", proxy_port); // 设置http代理
  37. //client.setSocketProxy("proxy_host", proxy_port); // 设置socket代理
  38. JSONObject res = client.asr(file, "pcm", 16000, null);
  39. //System.out.println(res.toString(2));
  40. System.out.println(res.get("result").toString());
  41. return res.get("result").toString();
  42. }
  43.  
  44. }

  

7、结果写入文件:

  1. package com.my.ai.service;
  2.  
  3. import java.io.BufferedOutputStream;
  4. import java.io.BufferedWriter;
  5. import java.io.File;
  6. import java.io.FileOutputStream;
  7. import java.io.FileWriter;
  8. import java.io.IOException;
  9. import java.io.OutputStreamWriter;
  10. import java.io.RandomAccessFile;
  11.  
  12. import org.slf4j.Logger;
  13. import org.slf4j.LoggerFactory;
  14. import org.springframework.stereotype.Service;
  15.  
  16. @Service
  17. public class FileService {
  18.  
  19. public static Logger logger = LoggerFactory.getLogger(FileService.class);
  20.  
  21. //最慢
  22. public static void writeFile1(String file,String content) throws IOException {
  23. FileOutputStream out = null;
  24. out = new FileOutputStream(new File(file));
  25. long begin = System.currentTimeMillis();
  26. out.write(content.getBytes());
  27. out.close();
  28. long end = System.currentTimeMillis();
  29. System.out.println("FileOutputStream执行耗时:" + (end - begin) + " 毫秒");
  30. }
  31. //中
  32. public static void writeFile2(String file,String content) throws IOException{
  33. FileWriter fw = null;
  34. fw = new FileWriter(file);
  35. long begin3 = System.currentTimeMillis();
  36. fw.write(content);
  37. fw.close();
  38. long end3 = System.currentTimeMillis();
  39. System.out.println("FileWriter执行耗时:" + (end3 - begin3) + " 毫秒");
  40. }
  41. //最快
  42. public static void writeFile3(String file,String content) throws IOException{
  43. FileOutputStream outSTr = null;
  44. BufferedOutputStream buff = null;
  45. outSTr = new FileOutputStream(new File(file));
  46. buff = new BufferedOutputStream(outSTr);
  47. long begin0 = System.currentTimeMillis();
  48. buff.write(content.getBytes());
  49. buff.flush();
  50. buff.close();
  51. long end0 = System.currentTimeMillis();
  52. System.out.println("BufferedOutputStream执行耗时:" + (end0 - begin0) + " 毫秒");
  53. }
  54.  
  55. public static void main(String[] args) {
  56. for (int i = 0; i < 7; i++) {
  57. String result = TokenService.getResult("E:\\QLDownload\\氧化还原反应中电子转移的方向和数目的表示方法\\" + i +"-氧化还原反应中电子转移的方向和数目的表示方法.pcm");
  58. appendFile2("E:\\QLDownload\\氧化还原反应中电子转移的方向和数目的表示方法\\氧化还原反应中电子转移的方向和数目的表示方法.txt", result+"\r\n");
  59. }
  60. }
  61.  
  62. public static void appendFile1(String file, String conent) {
  63. BufferedWriter out = null;
  64. try {
  65. out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
  66. out.write(conent);
  67. } catch (Exception e) {
  68. e.printStackTrace();
  69. } finally {
  70. try {
  71. if (out != null) {
  72. out.close();
  73. }
  74. } catch (IOException e) {
  75. e.printStackTrace();
  76. }
  77. }
  78. }
  79.  
  80. /**
  81. * 追加文件:使用FileWriter
  82. *
  83. * @param fileName
  84. * @param content
  85. */
  86. public static void appendFile2(String fileName, String content) {
  87. FileWriter writer = null;
  88. try {
  89. // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
  90. writer = new FileWriter(fileName, true);
  91. writer.write(content);
  92. } catch (IOException e) {
  93. e.printStackTrace();
  94. } finally {
  95. try {
  96. if (writer != null) {
  97. writer.close();
  98. }
  99. } catch (IOException e) {
  100. e.printStackTrace();
  101. }
  102. }
  103. }
  104.  
  105. /**
  106. * 追加文件:使用RandomAccessFile
  107. *
  108. * @param fileName 文件名
  109. * @param content 追加的内容
  110. */
  111. public static void appendFile3(String fileName, String content) {
  112. RandomAccessFile randomFile = null;
  113. try {
  114. // 打开一个随机访问文件流,按读写方式
  115. randomFile = new RandomAccessFile(fileName, "rw");
  116. // 文件长度,字节数
  117. long fileLength = randomFile.length();
  118. // 将写文件指针移到文件尾。
  119. randomFile.seek(fileLength);
  120. randomFile.writeBytes(content);
  121. } catch (IOException e) {
  122. e.printStackTrace();
  123. } finally {
  124. if (randomFile != null) {
  125. try {
  126. randomFile.close();
  127. } catch (IOException e) {
  128. e.printStackTrace();
  129. }
  130. }
  131. }
  132. }
  133.  
  134. }

 

8、测试:

  1. package com.my.ai.test;
  2.  
  3. import java.util.List;
  4.  
  5. import com.my.ai.service.CutService;
  6. import com.my.ai.service.ExtractAudioService;
  7. import com.my.ai.service.FileService;
  8. import com.my.ai.service.TokenService;
  9.  
  10. public class TestService {
  11.  
  12. public static void main(String[] args) {
  13. ExtractAudioService audioService = new ExtractAudioService();
  14. String outPath = audioService.getAudioFromVideo("G:\\Youku Files\\transcode\\化学高中必修1__第2章第3节·氧化还原反应_标清.mp4", "D:\\ffmpeg4.2\\bin\\ffmpeg.exe");
  15. List<String> audios = new CutService().cutFile(outPath,"D:\\ffmpeg4.2\\bin\\ffmpeg.exe");
  16. for (String wavPath : audios) {
  17. String out = wavPath.substring(0,wavPath.lastIndexOf(".")) + ".pcm";
  18. String outPcm = CutService.processWavToPcm(wavPath, "D:\\ffmpeg4.2\\bin\\ffmpeg.exe", out);
  19. String result = TokenService.getResult(outPcm);
  20. FileService.appendFile2("G:\\Youku Files\\transcode\\化学高中必修1__第2章第3节·氧化还原反应_标清.mp4-字幕.txt", result+"\r\n");
  21. }
  22. }
  23.  
  24. }

  

使用FFmpeg进行视频抽取音频,之后进行语音识别转为文字的更多相关文章

  1. ffmpeg实现视频文件合并/截取预览视频/抽取音频/crop(裁剪)(ffmpeg4.2.2)

    一,ffmpeg的安装 请参见: https://www.cnblogs.com/architectforest/p/12807683.html 说明:刘宏缔的架构森林是一个专注架构的博客,地址:ht ...

  2. 在java中使用FFmpeg处理视频与音频

    FFmpeg是一个非常好用的视频处理工具,下面讲讲如何在java中使用该工具类. 一.首先,让我们来认识一下FFmpeg在Dos界面的常见操作 1.拷贝视频,并指定新的视频的名字以及格式 ffmpeg ...

  3. FFmpeg开发实战(四):FFmpeg 抽取音视频的音频数据

    如何使用FFmpeg抽取音视频的音频数据,代码如下: void adts_header(char *szAdtsHeader, int dataLen); // 使用FFmpeg从视频中抽取音频 vo ...

  4. FFmpeg进行视频帧提取&音频重采样-Process.waitFor()引发的阻塞超时

    由于产品需要对视频做一系列的解析操作,利用FFmpeg命令来完成视频的音频提取.第一帧提取作为封面图片.音频重采样.字幕压缩等功能: 前一篇文章已经记录了FFmpeg在JAVA中的使用-音频提取&am ...

  5. Java使用FFmpeg处理视频文件指南

    Java使用FFmpeg处理视频文件指南 本文主要讲述如何使用Java + FFmpeg实现对视频文件的信息提取.码率压缩.分辨率转换等功能: 之前在网上浏览了一大圈Java使用FFmpeg处理音视频 ...

  6. Java使用FFmpeg处理视频文件的方法教程

    这篇文章主要给大家介绍了关于Java使用FFmpeg处理视频文件的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧 前言 本文主要 ...

  7. ffmpeg为视频添加时间戳 - 手动编译ffmpeg

    FFMPEG给视频加时间戳水印 项目中需要给视频添加时间戳,理所当然最好用的办法是ffmpeg.在找到正确的做法前,还被网上的答案timecode给水了一下(水的不轻,在这里转了2天),大概是这样写的 ...

  8. 使用ffmpeg 对视频截图,和视频转换格式

    //执行CMD命令方法 public static void CmdProcess(string command)//调用CMD        {            //实例化一个进程类      ...

  9. NET 2.0(C#)调用ffmpeg处理视频的方法

    另外:ffmpeg的net封装库 http://www.intuitive.sk/fflib/ NET 2.0 调用FFMPEG,并异步读取输出信息的代码...public void ConvertV ...

随机推荐

  1. 转载 二十篇java技术热文

    转自微信公众号:java知音 1,详解java类的生命周期 2,Java反射最佳实践 3,Spring的IOC原理 4,Java并发编程:volatile关键字解析 5,Java Thread 总结 ...

  2. 一步步来用C语言来写python扩展-乾颐堂

    本文介绍如何用 C 语言来扩展 python.所举的例子是,为 python 添加一个设置字符串到 windows 的剪切板(Clipboard)的功能.我在写以下代码的时候用到的环境是:window ...

  3. LoadRunner出现error问题及解决方法总结

    一.Step download timeout (120 seconds) 这是一个经常会遇到的问题,解决得办法走以下步骤:1.   修改run time setting中的请求超时时间,增加到600 ...

  4. jdk1.7 环境变量配置

    Windows系统中设置环境变量如下图右击“我的电脑”,选择“属性”. 点击“高级”选项卡,选择“环境变量”.  在“系统环境变量”中设置上面提到的3个环境变量,如果变量已经存在就选择“编辑”,否则选 ...

  5. 白盒测试实践--Day2

    累计完成任务情况: 阶段内容 参与人 完成CheckStyle检查 小靳 完成代码评审会议纪要和结果报告 小熊.小梁及其他 完成白盒测试用例 小尹 学习静态代码审核,确定评审表,开评审会确定高危区代码 ...

  6. myisam,innodb和memory的区别

    1.myisam,innodb和memory的区别如下: 2:InnoDB存储引擎2.1:InnoDB具有事务,回滚,崩溃修复能力和多版本并发的事务安全2.2:关于InnoDB的auto_increm ...

  7. Codeigniter框架前后台部署(多目录部署)

    个网站一般包含前台和后台并且访问的url是不同的,Codeigniter怎么来部署呢? 在网上看到了一篇比较好的文章: 在下载好的ci的根目录建立一个目录 admin 将application目录中的 ...

  8. pig配置

    下载Apache Pig 首先,从以下网站下载最新版本的Apache Pig:https://pig.apache.org/ 步骤1 打开Apache Pig网站的主页.在News部分下,点击链接re ...

  9. BZOJ 1977 严格次小生成树

    小C最近学了很多最小生成树的算法,Prim算法.Kurskal算法.消圈算法等等.正当小C洋洋得意之时,小P又来泼小C冷水了.小P说,让小C求出一个无向图的次小生成树,而且这个次小生成树还得是严格次小 ...

  10. Android-Activity横竖屏切换不杀死Activity 并监听横竖屏切换

    在上一篇博客,Android-Activity临时数据的保存,中讲解到,当发生横竖屏切换的时候,系统会杀死Activity并重新启动Activity 系统会杀死Activity 12-12 08:11 ...