7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PyAudio のサンプル

Posted at

PyAudio のサンプルです。

録音

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

# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
CHUNK = 1024
FORMAT = pyaudio.paInt16 # int16型
CHANNELS = 2             # ステレオ
RATE = 44100             # 441.kHz
RECORD_SECONDS = 5       # 5秒録音
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("*** 終了 ***\n")
# ------------------------------------------------------------------

実行方法

./record.py output.wav

再生

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

# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\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("*** 終了 ***\n")
# ------------------------------------------------------------------

実行方法

./play.py input.wav

参考ページ
PyAudio Documentation

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?