使用python播放wav语音

2019-07-20  本文已影响0人  安安爸Chris

实现的方法可能有很多种,这里我主要使用的是wave+pyAudio来实现。
阻塞调用方式

import os
import pyaudio
import wave

CHUNK = 1024

# 1. Get the file path to the included audio example
audio_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "audio")
audio_file =  os.path.join(audio_path, "node2.wav")
print("audio_file :",audio_file )

wf = wave.open(audio_file, 'rb')
print("samplewidth:", wf.getsampwidth())
print("channles:",wf.getnchannels())
print("framerate:",wf.getframerate())

p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels = wf.getnchannels(),
                rate= wf.getframerate(),
                output=True)
data = wf.readframes(CHUNK)

while len(data) >0:
    stream.write(data)
    data = wf.readframes(CHUNK)

stream.stop_stream()
stream.close()
wf.close()
p.terminate()

回调调用方式

import os
import pyaudio
import wave
import time

def callback(in_data, frame_count, time_info, status):
    data = wf.readframes(frame_count)
    return (data, pyaudio.paContinue)

# 1. Get the file path to the included audio example
audio_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "audio")
audio_file =  os.path.join(audio_path, "node2.wav")
print("audio_file :",audio_file )

wf = wave.open(audio_file, 'rb')
print("samplewidth:", wf.getsampwidth())
print("channles:",wf.getnchannels())
print("framerate:",wf.getframerate())

p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels = wf.getnchannels(),
                rate= wf.getframerate(),
                output=True,
                stream_callback=callback)
stream.start_stream()

while stream.is_active():
    time.sleep(0.1)

stream.stop_stream()
stream.close()
wf.close()
p.terminate()

具体参考文档如下
https://people.csail.mit.edu/hubert/pyaudio/docs/

上一篇下一篇

猜你喜欢

热点阅读