使用python播放wav语音

实现的方法可能有很多种,这里我主要使用的是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/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • --- layout: post title: "如果有人问你关系型数据库的原理,叫他看这篇文章(转)" date...
    蓝坠星阅读 825评论 0 3
  • Nature 论文 Mastering the game of Go without human knowledg...
    阿甘run阅读 1,608评论 0 1
  • python 令人大爱的想必是其简单的语法 方便快捷的开发速度及大量 精美好用的第三方包。今天我们来谈谈 py...
    Helen_Cat阅读 878评论 0 2
  • 1 什么是异步编程 通过学习相关概念,我们逐步解释异步编程是什么。 1.1 阻塞 程序未得到所需计算资源时被挂起的...
    hugoren阅读 2,689评论 2 10
  • 刚看了一本村上春树的随笔集,很想试试他那种平和的笔风。自己写的东西看上去总是那么烦恼。此刻“和”着一张爵士唱片(最...
    17c6927a4d6d阅读 288评论 0 0