使用pyaudio播放无损音乐(wav)
安装pyaudio
sudo apt-get install python-pyaudio python3-pyaudio pip3 install pyaudio
执行第二步可能会遇到如下错误:
根据网址的指导:
pip will download the PyAudio source and build it for your system. Be sure to install the portaudio library development package (portaudio19-dev
) and the python development package (python-all-dev
) beforehand.
需要安装portaudio19-dev和
python-all-dev
:
sudo apt-get install portaudio19-dev python-all-dev python3-all-dev
使用pyaudio播放wav音乐:
import pyaudio import wave import sys CHUNK = 1024 if len(sys.argv) < 2: print("Play a wave file.\n\nUsage: %s filename.wav" % sys.argv[0]) sys.exit(-1) wf = wave.open(sys.argv[1], 'rb') 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 data != '': stream.write(data) data = wf.readframes(CHUNK) stream.stop_stream() stream.close() p.terminate()