[PYTHON] PyAudio-Probe

Dies ist ein Beispiel für PyAudio.

Aufzeichnung

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 #Typ int16
CHANNELS = 2             #Stereo
RATE = 44100             # 441.kHz
RECORD_SECONDS = 5       #5 Sekunden Aufnahme
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("***Ende***\n")
# ------------------------------------------------------------------

Ausführungsmethode

./record.py output.wav

Wiedergabe

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("***Ende***\n")
# ------------------------------------------------------------------

Ausführungsmethode

./play.py input.wav

Referenzseite PyAudio Documentation

Recommended Posts

PyAudio-Probe
Probe abkratzen
Python-Abschlussbeispiel
Beispiel Adaptive MCMC
[PyTorch] Probe ② ~ TENSOR ~
[PyTorch] Beispiel ① ~ NUMPY ~
Beispiel für maschinelles Lernen