pyaudio官网:https://people.csail.mit.edu/hubert/pyaudio/docs/#pasampleformat
通过绑定空格键,控制音乐播放、暂停功能。
import pyaudio
import wave
import time
import keyboard
import threading
import queue
import numpy
chunk = 576
que = queue.Queue()
AUDIO_PLAY_STATE_PLAY = 1
AUDIO_PLAY_STATE_PAUSE = 2
AUDIO_PLAY_STATE_END = 4
playState = AUDIO_PLAY_STATE_PLAY
def on_space_press():
global playState
if playState == AUDIO_PLAY_STATE_PLAY:
playState = AUDIO_PLAY_STATE_PAUSE
print("暂停")
else :
playState = AUDIO_PLAY_STATE_PLAY
print("播放")
# 设置空格键的回调函数
keyboard.add_hotkey('space', on_space_press)
def add_data():
global que
# 打开音频文件
filename = '1276002468.wav'
wf = wave.open(filename, 'rb')
data = wf.readframes(chunk)
while data:
que.put(data)
#time.sleep(0.75)
data = wf.readframes(chunk)
print("add_data:", len(data))
wf.close()
def callback(in_data, frame_count, time_info, status):
global playState
global que
if playState == AUDIO_PLAY_STATE_PLAY:
data = que.get(timeout=0.5)
print(len(data), frame_count)
if len(data) >= frame_count:
status = pyaudio.paContinue
else :
status = pyaudio.paComplete
playState = AUDIO_PLAY_STATE_END
else:
data = numpy.zeros(frame_count*2).tostring()
status = pyaudio.paContinue
return (data, status)
def music_play():
global que
global is_play
global stream
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.get_format_from_width(2),
channels=2,
rate=44100,
output=True,
output_device_index = 3,
stream_callback=callback)
while stream.is_active():
time.sleep(0.1)
stream.stop_stream()
stream.close()
p.terminate()
if __name__ == "__main__":
thread1 = threading.Thread(target=add_data)
thread1.start()
thread2 = threading.Thread(target=music_play)
thread2.start()
thread1.join()
thread2.join()
print("All threads have finished execution.")