ConvertUtils.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package com.jd.util;
  2. import java.io.*;
  3. import com.jd.util.WaveHeader;
  4. /**
  5. * @Author: clf
  6. * @Date: 2020-03-08
  7. * @Description: 语音合成工具类
  8. */
  9. public class ConvertUtils {
  10. /**
  11. * 转换音频文件
  12. * @param src 需要转换的pcm音频路径
  13. * @param target 保存转换后wav格式的音频路径
  14. * @throws Exception
  15. */
  16. public static void convertPcm2Wav(String src, String target) throws Exception {
  17. FileInputStream fis = new FileInputStream(src);
  18. FileOutputStream fos = new FileOutputStream(target);
  19. //计算长度
  20. byte[] buf = new byte[1024 * 4];
  21. int size = fis.read(buf);
  22. int PCMSize = 0;
  23. while (size != -1) {
  24. PCMSize += size;
  25. size = fis.read(buf);
  26. }
  27. fis.close();
  28. //填入参数,比特率等等。这里用的是16位单声道 8000 hz
  29. WaveHeader header = new WaveHeader();
  30. //长度字段 = 内容的大小(PCMSize) + 头部字段的大小(不包括前面4字节的标识符RIFF以及fileLength本身的4字节)
  31. header.fileLength = PCMSize + (44 - 8);
  32. header.FmtHdrLeth = 16;
  33. header.BitsPerSample = 16;
  34. header.Channels = 2;
  35. header.FormatTag = 0x0001;
  36. header.SamplesPerSec = 8000;
  37. header.BlockAlign = (short)(header.Channels * header.BitsPerSample / 8);
  38. header.AvgBytesPerSec = header.BlockAlign * header.SamplesPerSec;
  39. header.DataHdrLeth = PCMSize;
  40. byte[] h = header.getHeader();
  41. assert h.length == 44; //WAV标准,头部应该是44字节
  42. //write header
  43. fos.write(h, 0, h.length);
  44. //write data stream
  45. fis = new FileInputStream(src);
  46. size = fis.read(buf);
  47. while (size != -1) {
  48. fos.write(buf, 0, size);
  49. size = fis.read(buf);
  50. }
  51. fis.close();
  52. fos.close();
  53. System.out.println("Convert OK!");
  54. }
  55. }