play_sound.py 1.08 KB
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()