There are several ways to use python to play audio:
os.system()
os.system(file ) Call the system application to open the file. file can be an image or audio file.
Disadvantages: To open a specific application, audio cannot be played in the background.
pyaudio
Installation: pip install pyaudio
The official API for playing audio and recording is very convenient to use. Just put Filename Change the text to your audio file and you can play the audio.
"""PyAudio Example: Play a WAVE file.""" import pyaudio import wave CHUNK = 1024 FILENAME = '你的音频文件' def play(filename = FILENAME): wf = wave.open(filename, '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 != b'': stream.write(data) data = wf.readframes(CHUNK) stream.stop_stream() stream.close() p.terminate()
jupyter notebook
You can use the following functions to play audio in jupyer notebook:
import IPython.display as ipd ipd.Audio(文件名)
For more Python related technical articles, please visitPython tutorialcolumn for learning!
The above is the detailed content of How to play audio using python. For more information, please follow other related articles on the PHP Chinese website!