pythonでキーボードの入力で音声録音を保存する方法

pythonでキーボードの入力で音声録音を保存する方法


音声の録音

Enterで録音を停止

import pyaudio
import wave
import threading

class Record:
    def __init__(self, chunksize=1024, nchannels=1, fs=44100):
        self.CHUNK = chunksize
        self.FORMAT = pyaudio.paInt16
        self.NCHANNELS = nchannels
        self.RATE = fs
        self.rec_sig = []
        self.command = None
        self.p = pyaudio.PyAudio()

    def __del__(self):
        self.p.terminate()

    def callback(self, in_data, frame_count, time_info, status_flags):
        self.rec_sig.append(in_data)
        if self.command == "":
            return None, pyaudio.paComplete
        return None, pyaudio.paContinue

    def recording(self, filename):
        stream = self.p.open(
            format=self.FORMAT,
            channels=self.NCHANNELS,
            rate=self.RATE,
            input=True,
            frames_per_buffer=self.CHUNK,
            stream_callback=self.callback
        )

        stream.start_stream()

        # 別スレッドでユーザー入力を待機
        input_thread = threading.Thread(target=self.wait_for_input)
        input_thread.start()

        while stream.is_active():
            if self.command == "":
                break

        stream.stop_stream()
        stream.close()
        wf = wave.open(filename, 'wb')
        wf.setnchannels(self.NCHANNELS)
        wf.setsampwidth(self.p.get_sample_size(self.FORMAT))
        wf.setframerate(self.RATE)
        wf.writeframes(b''.join(self.rec_sig))
        wf.close()

    def wait_for_input(self):
        input("Press Enter to stop recording...")
        self.command = ""

if __name__ == "__main__":
    chunksize = 1024
    nchannels = 1
    fs = 44100
    filename = "./output.wav"
    rec = Record(chunksize, nchannels, fs)
    rec.recording(filename)


Enterで録音を停止、wavで保存し、新たな録音を開始する。(aで停止)

import pyaudio
import wave
import threading

class Record:
    def __init__(self, chunksize, nchannels, fs, filepath):
        self.CHUNK = chunksize
        self.FORMAT = pyaudio.paInt16
        self.NCHANNELS = nchannels
        self.RATE = fs
        self.filepath = filepath
        self.rec_sig = []
        self.command = None
        self.p = pyaudio.PyAudio()
        self.recording_num = 0

    def __del__(self):
        self.p.terminate()

    def callback(self, in_data, frame_count, time_info, status_flags):
        self.rec_sig.append(in_data)
        if self.command == "":
            return None, pyaudio.paComplete
        if self.command == "a":
            return
        return None, pyaudio.paContinue

    def recording(self):
        while self.command != "a":
            self.rec_sig = []
            self.recording_num += 1
            filename = f"{self.filepath}_{self.recording_num}.wav"
            stream = self.p.open(
                format=self.FORMAT,
                channels=self.NCHANNELS,
                rate=self.RATE,
                input=True,
                frames_per_buffer=self.CHUNK,
                stream_callback=self.callback
            )

            stream.start_stream()

            # 別スレッドでユーザー入力を待機
            input_thread = threading.Thread(target=self.wait_for_input)
            input_thread.start()

            while stream.is_active():
                if self.command == "" or self.command == "a":
                    break

            stream.stop_stream()
            stream.close()
            wf = wave.open(filename, 'wb')
            wf.setnchannels(self.NCHANNELS)
            wf.setsampwidth(self.p.get_sample_size(self.FORMAT))
            wf.setframerate(self.RATE)
            wf.writeframes(b''.join(self.rec_sig))
            wf.close()

            if self.command == "":
                self.command = None  # Reset command for the next recording

    def wait_for_input(self):
        while True:
            self.command = input("Press Enter to stop recording and start a new one, or 'a' to exit: ")
            if self.command == "a" or self.command == "":
                break

if __name__ == "__main__":
    chunksize = 1024
    nchannels = 1
    filepath = "/Users/Downloads/segments/"
    fs = 44100
    rec = Record(chunksize, nchannels, fs, filepath)
    rec.recording()

Comments

No comments yet. Why don’t you start the discussion?

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です