【PyAudio】音声を録音する

PyAudioを用いて、入力した音声をwavファイルに書き出す。

import pyaudio
import wave

filename = "sample.wav"

fs = 44100
sec = 3
CHUNK = 1024

p = pyaudio.PyAudio()

stream = p.open(format=pyaudio.paInt16,
                channels=1,
                rate=fs,
                frames_per_buffer=CHUNK,
                input=True)

bin = []
for i in range(int(fs * sec / CHUNK)):
  data = stream.read(CHUNK)
  bin.append(data)
data = stream.read(fs * sec % CHUNK)
bin.append(data)

bin = b''.join(bin)

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

w = wave.Wave_write(filename)
p = (1, 2, fs, len(bin), 'NONE', 'not compressed')
w.setparams(p)
w.writeframes(bin)
w.close()
タイトルとURLをコピーしました