play_sound.py
1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from pydub import AudioSegment
import pyaudio
import numpy as np
# Usage:
file_path = "./sounds/s1.mp3"
audio_file = AudioSegment.from_mp3(file_path)
print(audio_file.frame_rate)
print(audio_file.sample_width)
print(audio_file.channels)
raw_audio_data = np.frombuffer(AudioSegment.from_mp3("./sounds/wooAk.mp3").raw_data, dtype=np.int16)
p = pyaudio.PyAudio()
idx = 0
def callback(in_data, frame_count, time_info, status):
global raw_audio_data
global idx
idx += frame_count
chunk = raw_audio_data[idx:idx+frame_count]
if len(chunk) < frame_count:
chunk = np.concatenate((chunk, np.zeros(frame_count - len(chunk), dtype=np.int16)))
idx = 0
return (chunk, pyaudio.paContinue)
stream = p.open(format=p.get_format_from_width(audio_file.sample_width),
channels=audio_file.channels,
rate=audio_file.frame_rate,
output_device_index=2,
output=True,
stream_callback=callback)
stream.start_stream()
while stream.is_active():
pass
stream.stop_stream()
stream.close()
p.terminate()