LoginSignup
67
73

More than 3 years have passed since last update.

Pythonで音を監視して一定以上の音量を録音する

Last updated at Posted at 2018-02-17

はじめに

「音をテーマに機械学習の題材を調査する」という宿題を頂いたことから、一定のルールで継続的に音を収集する方法を検討したのでメモします。

ちなみに、環境設定などは以下の記事をご参照下さい。

Pythonで音を録音して可視化する

閾値を超えたら2秒間録音

以下のスクリプトを作成する。

record2sec.py
#!/usr/bin/env python

# ライブラリの読込
import pyaudio
import wave
import numpy as np
from datetime import datetime

# 音データフォーマット
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 2

# 閾値
threshold = 0.01

# 音の取込開始
p = pyaudio.PyAudio()
stream = p.open(format = FORMAT,
    channels = CHANNELS,
    rate = RATE,
    input = True,
    frames_per_buffer = chunk
)

cnt = 0

while True:
    # 音データの取得
    data = stream.read(chunk)
    # ndarrayに変換
    x = np.frombuffer(data, dtype="int16") / 32768.0

    # 閾値以上の場合はファイルに保存
    if x.max() > threshold:
        filename = datetime.today().strftime("%Y%m%d%H%M%S") + ".wav"
        print(cnt, filename)

        # 2秒間の音データを取込
        all = []
        all.append(data)
        for i in range(0, int(RATE / chunk * int(RECORD_SECONDS))):
            data = stream.read(chunk)
            all.append(data)
        data = b''.join(all)

        # 音声ファイルとして出力
        out = wave.open(filename,'w')
        out.setnchannels(CHANNELS)
        out.setsampwidth(2)
        out.setframerate(RATE)
        out.writeframes(data)
        out.close()

        print("Saved.")

        cnt += 1

    # 5回検出したら終了
    if cnt > 5:
        break

stream.close()
p.terminate()

動作確認と閾値調整

以下のコマンドを実行すると、閾値以上の音量の音が鳴ると自動的に発生日時をファイル名としたWAVファイルが出力されます。

chmod a+x record2sec.py
./record2sec.py

検出したい音量が検出できるよう閾値(threshold)を調整。

データ収集

調整ができたら以下のとおりスクリプトを変更。

    #    cnt += 1
    #if cnt > 5:
    #    break

コメントアウト後、以下のコマンドを実行すると継続的に音を収集し、WAVファイルを生成します。

./record2sec.py &

できた!

これをRaspberry PIなどを使って自動的に実行させれば、音が収集できて機械学習に利用できるかも...(続く)

67
73
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
67
73