Home  >  Article  >  Backend Development  >  How to play audio using python

How to play audio using python

尚
Original
2019-06-26 13:51:5211145browse

How to play audio using python

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 visit Python tutorial column 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn