You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

134 lines
3.9KB

  1. import shutil
  2. import wave
  3. from common.log import logger
  4. try:
  5. import pysilk
  6. except ImportError:
  7. logger.warn("import pysilk failed, wechaty voice message will not be supported.")
  8. from pydub import AudioSegment
  9. sil_supports = [8000, 12000, 16000, 24000, 32000, 44100, 48000] # slk转wav时,支持的采样率
  10. def find_closest_sil_supports(sample_rate):
  11. """
  12. 找到最接近的支持的采样率
  13. """
  14. if sample_rate in sil_supports:
  15. return sample_rate
  16. closest = 0
  17. mindiff = 9999999
  18. for rate in sil_supports:
  19. diff = abs(rate - sample_rate)
  20. if diff < mindiff:
  21. closest = rate
  22. mindiff = diff
  23. return closest
  24. def get_pcm_from_wav(wav_path):
  25. """
  26. 从 wav 文件中读取 pcm
  27. :param wav_path: wav 文件路径
  28. :returns: pcm 数据
  29. """
  30. wav = wave.open(wav_path, "rb")
  31. return wav.readframes(wav.getnframes())
  32. def any_to_mp3(any_path, mp3_path):
  33. """
  34. 把任意格式转成mp3文件
  35. """
  36. if any_path.endswith(".mp3"):
  37. shutil.copy2(any_path, mp3_path)
  38. return
  39. if any_path.endswith(".sil") or any_path.endswith(".silk") or any_path.endswith(".slk"):
  40. sil_to_wav(any_path, any_path)
  41. any_path = mp3_path
  42. audio = AudioSegment.from_file(any_path)
  43. audio.export(mp3_path, format="mp3")
  44. def any_to_wav(any_path, wav_path):
  45. """
  46. 把任意格式转成wav文件
  47. """
  48. if any_path.endswith(".wav"):
  49. shutil.copy2(any_path, wav_path)
  50. return
  51. if any_path.endswith(".sil") or any_path.endswith(".silk") or any_path.endswith(".slk"):
  52. return sil_to_wav(any_path, wav_path)
  53. audio = AudioSegment.from_file(any_path)
  54. audio.export(wav_path, format="wav")
  55. def any_to_sil(any_path, sil_path):
  56. """
  57. 把任意格式转成sil文件
  58. """
  59. if any_path.endswith(".sil") or any_path.endswith(".silk") or any_path.endswith(".slk"):
  60. shutil.copy2(any_path, sil_path)
  61. return 10000
  62. audio = AudioSegment.from_file(any_path)
  63. rate = find_closest_sil_supports(audio.frame_rate)
  64. # Convert to PCM_s16
  65. pcm_s16 = audio.set_sample_width(2)
  66. pcm_s16 = pcm_s16.set_frame_rate(rate)
  67. wav_data = pcm_s16.raw_data
  68. silk_data = pysilk.encode(wav_data, data_rate=rate, sample_rate=rate)
  69. with open(sil_path, "wb") as f:
  70. f.write(silk_data)
  71. return audio.duration_seconds * 1000
  72. def any_to_amr(any_path, amr_path):
  73. """
  74. 把任意格式转成amr文件
  75. """
  76. if any_path.endswith(".amr"):
  77. shutil.copy2(any_path, amr_path)
  78. return
  79. if any_path.endswith(".sil") or any_path.endswith(".silk") or any_path.endswith(".slk"):
  80. raise NotImplementedError("Not support file type: {}".format(any_path))
  81. audio = AudioSegment.from_file(any_path)
  82. audio = audio.set_frame_rate(8000) # only support 8000
  83. audio.export(amr_path, format="amr")
  84. return audio.duration_seconds * 1000
  85. def sil_to_wav(silk_path, wav_path, rate: int = 24000):
  86. """
  87. silk 文件转 wav
  88. """
  89. wav_data = pysilk.decode_file(silk_path, to_wav=True, sample_rate=rate)
  90. with open(wav_path, "wb") as f:
  91. f.write(wav_data)
  92. def split_audio(file_path, max_segment_length_ms=60000):
  93. """
  94. 分割音频文件
  95. """
  96. audio = AudioSegment.from_file(file_path)
  97. audio_length_ms = len(audio)
  98. if audio_length_ms <= max_segment_length_ms:
  99. return audio_length_ms, [file_path]
  100. segments = []
  101. for start_ms in range(0, audio_length_ms, max_segment_length_ms):
  102. end_ms = min(audio_length_ms, start_ms + max_segment_length_ms)
  103. segment = audio[start_ms:end_ms]
  104. segments.append(segment)
  105. file_prefix = file_path[: file_path.rindex(".")]
  106. format = file_path[file_path.rindex(".") + 1 :]
  107. files = []
  108. for i, segment in enumerate(segments):
  109. path = f"{file_prefix}_{i+1}" + f".{format}"
  110. segment.export(path, format=format)
  111. files.append(path)
  112. return audio_length_ms, files