To create a Python audio player, you can use the pyaudio
and wave
modules to load and play audio files. Here’s an example:
import pyaudio
import wave
chunk = 1024
# Open the audio file
wf = wave.open('audio_file.wav', 'rb')
# Initialize PyAudio
p = pyaudio.PyAudio()
# Open the stream
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True)
# Read data from the file and play it
data = wf.readframes(chunk)
while data != b'':
stream.write(data)
data = wf.readframes(chunk)
# Stop and close the stream
stream.stop_stream()
stream.close()
# Terminate PyAudio
p.terminate()
In this code, the wave
module is used to open an audio file in read mode, and the pyaudio
module is used to open a stream and play the audio. The audio file is read in chunks of 1024 bytes and played using the write()
method of the stream. Once the end of the file is reached, the stream is stopped and closed, and PyAudio is terminated.
To play a different audio file, simply replace 'audio_file.wav'
with the path to the desired audio file.
This is a simple example that plays an audio file in blocking mode, which means that the code will wait until the entire audio file is played before continuing. You can also use non-blocking mode to play audio in the background while the code continues to execute.
Overall, creating a Python audio player involves using the pyaudio
and wave
modules to load and play audio files, and customizing the code to suit your specific needs.
+ There are no comments
Add yours