PyAudio sample

This is a sample of PyAudio.

recording

record.py


#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#	record.py
#
#						Oct/02/2020
# ------------------------------------------------------------------
import	sys
import	pyaudio
import	wave

# ------------------------------------------------------------------
sys.stderr.write("***start***\n")
#
CHUNK = 1024
FORMAT = pyaudio.paInt16 #int16 type
CHANNELS = 2             #stereo
RATE = 44100             # 441.kHz
RECORD_SECONDS = 5       #5 seconds recording
WAVE_OUTPUT_FILENAME = sys.argv[1]

sys.stderr.write(WAVE_OUTPUT_FILENAME + "\n")

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

sys.stderr.write("* recording *\n")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

sys.stderr.write("* done recording *\n")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
#
sys.stderr.write("***End***\n")
# ------------------------------------------------------------------

Execution method

./record.py output.wav

Playback

play.py


#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#	play.py
#
#						Oct/02/2020
# ------------------------------------------------------------------
import	pyaudio
import	wave
import	sys

# ------------------------------------------------------------------
sys.stderr.write("***start***\n")
#
CHUNK = 1024

if len(sys.argv) < 2:
	print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
	sys.exit(-1)

sys.stderr.write(sys.argv[1] + "\n")

wf = wave.open(sys.argv[1], 'rb')

# instantiate PyAudio (1)
p = pyaudio.PyAudio()

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

# read data
data = wf.readframes(CHUNK)

# play stream (3)
while len(data) > 0:
	stream.write(data)
	data = wf.readframes(CHUNK)

# stop stream (4)
stream.stop_stream()
stream.close()

# close PyAudio (5)
p.terminate()
#
sys.stderr.write("***End***\n")
# ------------------------------------------------------------------

Execution method

./play.py input.wav

Reference page PyAudio Documentation

Recommended Posts

PyAudio sample
Scraping sample
Python closure sample
Sample Adaptive MCMC
[PyTorch] Sample ② ~ TENSOR ~
[PyTorch] Sample ① ~ NUMPY ~
Machine Learning sample