Skip to content

Instantly share code, notes, and snippets.

@tatesuke
Created April 10, 2019 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tatesuke/238993d01596964e3f4025f7d079343e to your computer and use it in GitHub Desktop.
Save tatesuke/238993d01596964e3f4025f7d079343e to your computer and use it in GitHub Desktop.
pythonによる録音サンプル
PyAudio‑0.2.11‑cp37‑cp37m‑win_amd64.whl を探してきてpip installしておく
import pyaudio #録音機能を使うためのライブラリ
import wave #wavファイルを扱うためのライブラリ
import datetime
RECORD_SECONDS = 10 #録音する時間の長さ(秒)
WAVE_OUTPUT_FILENAME = "%d.wav" % datetime.datetime.now().timestamp() #音声を保存するファイル名
iDeviceIndex = 0 #録音デバイスのインデックス番号
#基本情報の設定
FORMAT = pyaudio.paInt16 #音声のフォーマット
CHANNELS = 1 #モノラル
RATE = 44100 #サンプルレート
CHUNK = 2**11 #データ点数
audio = pyaudio.PyAudio() #pyaudio.PyAudio()
stream = audio.open(format=FORMAT, channels=CHANNELS,
rate=RATE, input=True,
input_device_index = iDeviceIndex, #録音デバイスのインデックス番号
frames_per_buffer=CHUNK)
#--------------録音開始---------------
print ("recording...")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print ("finished recording")
#--------------録音終了---------------
stream.stop_stream()
stream.close()
audio.terminate()
waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(frames))
waveFile.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment