Code for How to Play and Record Audio in Python Tutorial


View on Github

audio_player_playsound.py

from playsound import playsound

playsound("audio_file.mp3")

audio_player_pydub.py

from pydub import AudioSegment
from pydub.playback import play

# read MP3 file
song = AudioSegment.from_mp3("audio_file.mp3")
# song = AudioSegment.from_wav("audio_file.wav")
# you can also read from other formats such as MP4
# song = AudioSegment.from_file("audio_file.mp4", "mp4")
play(song)

audio_player_pyaudio.py

import pyaudio
import wave

filename = "audio_file.wav"

# set the chunk size of 1024 samples
chunk = 1024

# open the audio file
wf = wave.open(filename, "rb")

# initialize PyAudio object
p = pyaudio.PyAudio()

# open stream object
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True)

# read data in chunks
data = wf.readframes(chunk)

# writing to the stream (playing audio)
while data:
    stream.write(data)
    data = wf.readframes(chunk)

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

audio_recorder.py

import pyaudio
import wave

# the file name output you want to record into
filename = "recorded.wav"
# set the chunk size of 1024 samples
chunk = 1024
# sample format
FORMAT = pyaudio.paInt16
# mono, change to 2 if you want stereo
channels = 1
# 44100 samples per second
sample_rate = 44100
record_seconds = 5

# initialize PyAudio object
p = pyaudio.PyAudio()

# open stream object as input & output
stream = p.open(format=FORMAT,
                channels=channels,
                rate=sample_rate,
                input=True,
                output=True,
                frames_per_buffer=chunk)

frames = []
print("Recording...")
for i in range(int(sample_rate / chunk * record_seconds)):
    data = stream.read(chunk)
    # if you want to hear your voice while recording
    # stream.write(data)
    frames.append(data)
print("Finished recording.")
# stop and close stream
stream.stop_stream()
stream.close()
# terminate pyaudio object
p.terminate()

# save audio file
# open the file in 'write bytes' mode
wf = wave.open(filename, "wb")
# set the channels
wf.setnchannels(channels)
# set the sample format
wf.setsampwidth(p.get_sample_size(FORMAT))
# set the sample rate
wf.setframerate(sample_rate)
# write the frames as bytes
wf.writeframes(b"".join(frames))
# close the file
wf.close()