暂时记录两种方式,分别为使用“pydub+ffmpeg+simpleaudio”和“librosa+simpleaudio”,推荐第二种

使用pydub库读取音频、simpleaudio库播放音频

环境配置

Windows10环境下

  1. pip install pydub

  2. pip install simpleaudio

  3. 安装ffmpeg
    从https://www.gyan.dev/ffmpeg/builds/下载ffmpeg(压缩包),解压后将bin文件所在位置加入Path环境变量,并在相应程序中添加一行代码。具体操作参考以下三个链接:
    https://blog.csdn.net/qq_38161040/article/details/91654183
    https://cloud.tencent.com/developer/article/1702673
    https://www.freesion.com/article/6184901177/

  4. 注意该步骤不是用pip安装

  5. 重启计算机!(重要)

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from pydub import AudioSegment
import simpleaudio

def play_data_from_pydub(audio_segment):
player = simpleaudio.play_buffer(
​ audio_segment.raw_data,
​ num_channels=audio_segment.channels,
​ bytes_per_sample=audio_segment.sample_width,
​ sample_rate=audio_segment.frame_rate
)
try:
​ player.wait_done()
except KeyboardInterrupt:
​ player.stop()

if __name__ == '__main__':
audio_path = r'audio\test.mp3'

if (audio_path[-3:] == 'wav'): audio_seg = AudioSegment.from_file(audio_path, 'wav')
elif (audio_path[-3:] == 'mp3'): audio_seg = AudioSegment.from_file(audio_path, 'mp3')
play_data_from_pydub(audio_seg)

使用librosa库读取音频、simpleaudio库播放音频

环境配置

Windows10环境下

  1. pip install librosa
  2. pip install simpleaudio

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import simpleaudio
import librosa

def play_data_from_librosa(y, sr):
player = simpleaudio.play_buffer(
y,
num_channels=1,
bytes_per_sample=4,
sample_rate=sr
)
try:
player.wait_done()
except KeyboardInterrupt:
player.stop()

if __name__ == '__main__':
audio_path = r'audio\test.mp3'

y, sr = librosa.load(audio_path)
play_data_from_librosa(y, sr)