[PYTHON] Échantillon PyAudio

Ceci est un échantillon de PyAudio.

enregistrement

record.py


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

# ------------------------------------------------------------------
sys.stderr.write("***début***\n")
#
CHUNK = 1024
FORMAT = pyaudio.paInt16 #type int16
CHANNELS = 2             #stéréo
RATE = 44100             # 441.kHz
RECORD_SECONDS = 5       #Enregistrement de 5 secondes
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("***Fin***\n")
# ------------------------------------------------------------------

Méthode d'exécution

./record.py output.wav

Relecture

play.py


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

# ------------------------------------------------------------------
sys.stderr.write("***début***\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("***Fin***\n")
# ------------------------------------------------------------------

Méthode d'exécution

./play.py input.wav

Page de référence PyAudio Documentation

Recommended Posts

Échantillon PyAudio
Échantillon de grattage
Exemple de fermeture Python
Exemple de MCMC adaptatif
[PyTorch] Échantillon ② ~ TENSOR ~
[PyTorch] Exemple ① ~ NUMPY ~
Exemple d'apprentissage automatique