AudioProcessorObject.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import subprocess
  2. import os
  3. import subprocess
  4. class AudioProcessor:
  5. def __init__(self, default_sample_rate=8000, default_channels=1):
  6. """
  7. 初始化音频处理器,并设定默认采样率和声道数。
  8. 参数:
  9. default_sample_rate (int): 默认采样率,以赫兹(Hz)计。
  10. default_channels (int): 默认音频通道数。
  11. """
  12. self.default_sample_rate = default_sample_rate
  13. self.default_channels = default_channels
  14. def convert_audio(self, input_path, output_path):
  15. """
  16. 使用FFmpeg进行音频文件转换。
  17. 参数:
  18. input_path (str): 输入音频文件的路径。
  19. output_path (str): 输出音频文件的路径。
  20. """
  21. # 确定输入和输出文件类型
  22. input_ext = input_path.split('.')[-1]
  23. output_ext = output_path.split('.')[-1]
  24. # 构建FFmpeg命令
  25. ffmpeg_cmd = ['ffmpeg', '-y']
  26. # 设置输入格式参数
  27. if input_ext == 'g711a':
  28. ffmpeg_cmd.extend(['-f', 'alaw', '-ar', '8000', '-ac', '1'])
  29. ffmpeg_cmd.extend(['-i', input_path])
  30. # 设置输出格式参数
  31. if output_ext == 'pcm':
  32. ffmpeg_cmd.extend(['-acodec', 'pcm_s16le', '-f', 's16le'])
  33. elif output_ext == 'g711a':
  34. ffmpeg_cmd.extend(['-ar', '8000', '-ac', '1', '-acodec', 'pcm_alaw', '-f', 'alaw'])
  35. ffmpeg_cmd.append(output_path)
  36. # 执行FFmpeg命令
  37. command = ' '.join(ffmpeg_cmd)
  38. print(command) # 输出命令用于调试
  39. subprocess.run(command, shell=True, check=True)