如何用pyaudio播放音频文件? [英] How to play an audiofile with pyaudio?

查看:254
本文介绍了如何用pyaudio播放音频文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不了解pyaudio的示例材料.看来他们写了一个完整的小程序,这让我失望了.

I do not understand the example material for pyaudio. It seems they had written an entire small program and it threw me off.

如何仅播放单个音频文件?

How do I just play a single audio file?

格式不是问题,我只想知道播放音频文件所需的最少代码.

Format is not an issue, I just want to know the bare minimum code I need to play an audio file.

推荐答案

该示例对我来说似乎很清楚.您只需将示例另存为playwav.py调用:

The example seems pretty clear to me. You simply save the example as playwav.py call:

python playwav.py my_fav_wav.wav

带有一些额外注释的wave示例:

The wave example with some extra comments:

import pyaudio
import wave
import sys

# length of data to read.
chunk = 1024

# validation. If a wave file hasn't been specified, exit.
if len(sys.argv) < 2:
    print "Plays a wave file.\n\n" +\
          "Usage: %s filename.wav" % sys.argv[0]
    sys.exit(-1)

'''
************************************************************************
      This is the start of the "minimum needed to read a wave"
************************************************************************
'''
# open the file for reading.
wf = wave.open(sys.argv[1], 'rb')

# create an audio object
p = pyaudio.PyAudio()

# open stream based on the wave object which has been input.
stream = p.open(format =
                p.get_format_from_width(wf.getsampwidth()),
                channels = wf.getnchannels(),
                rate = wf.getframerate(),
                output = True)

# read data (based on the chunk size)
data = wf.readframes(chunk)

# play stream (looping from beginning of file to the end)
while data != '':
    # writing to the stream is what *actually* plays the sound.
    stream.write(data)
    data = wf.readframes(chunk)

# cleanup stuff.
stream.close()    
p.terminate()

这篇关于如何用pyaudio播放音频文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆