Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

83 lines
2.3KB

  1. import shutil
  2. import wave
  3. import pysilk
  4. from pydub import AudioSegment
  5. def get_pcm_from_wav(wav_path):
  6. """
  7. 从 wav 文件中读取 pcm
  8. :param wav_path: wav 文件路径
  9. :returns: pcm 数据
  10. """
  11. wav = wave.open(wav_path, "rb")
  12. return wav.readframes(wav.getnframes())
  13. def any_to_wav(any_path, wav_path):
  14. """
  15. 把任意格式转成wav文件
  16. """
  17. if any_path.endswith('.wav'):
  18. shutil.copy2(any_path, wav_path)
  19. return
  20. if any_path.endswith('.sil') or any_path.endswith('.silk') or any_path.endswith('.slk'):
  21. return sil_to_wav(any_path, wav_path)
  22. audio = AudioSegment.from_file(any_path)
  23. audio.export(wav_path, format="wav")
  24. def any_to_sil(any_path, sil_path):
  25. """
  26. 把任意格式转成sil文件
  27. """
  28. if any_path.endswith('.sil') or any_path.endswith('.silk') or any_path.endswith('.slk'):
  29. shutil.copy2(any_path, sil_path)
  30. return 10000
  31. if any_path.endswith('.wav'):
  32. return pcm_to_sil(any_path, sil_path)
  33. if any_path.endswith('.mp3'):
  34. return mp3_to_sil(any_path, sil_path)
  35. raise NotImplementedError("Not support file type: {}".format(any_path))
  36. def mp3_to_wav(mp3_path, wav_path):
  37. """
  38. 把mp3格式转成pcm文件
  39. """
  40. audio = AudioSegment.from_mp3(mp3_path)
  41. audio.export(wav_path, format="wav")
  42. def pcm_to_sil(pcm_path, silk_path):
  43. """
  44. wav 文件转成 silk
  45. return 声音长度,毫秒
  46. """
  47. audio = AudioSegment.from_wav(pcm_path)
  48. wav_data = audio.raw_data
  49. silk_data = pysilk.encode(
  50. wav_data, data_rate=audio.frame_rate, sample_rate=audio.frame_rate)
  51. with open(silk_path, "wb") as f:
  52. f.write(silk_data)
  53. return audio.duration_seconds * 1000
  54. def mp3_to_sil(mp3_path, silk_path):
  55. """
  56. mp3 文件转成 silk
  57. return 声音长度,毫秒
  58. """
  59. audio = AudioSegment.from_mp3(mp3_path)
  60. wav_data = audio.raw_data
  61. silk_data = pysilk.encode(
  62. wav_data, data_rate=audio.frame_rate, sample_rate=audio.frame_rate)
  63. # Save the silk file
  64. with open(silk_path, "wb") as f:
  65. f.write(silk_data)
  66. return audio.duration_seconds * 1000
  67. def sil_to_wav(silk_path, wav_path, rate: int = 24000):
  68. """
  69. silk 文件转 wav
  70. """
  71. wav_data = pysilk.decode_file(silk_path, to_wav=True, sample_rate=rate)
  72. with open(wav_path, "wb") as f:
  73. f.write(wav_data)