您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關使用python實現錄音功能并可隨時停止錄音,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
# -*- coding: utf-8 -*- import pyaudio import time import threading import wave class Recorder(): def __init__(self, chunk=1024, channels=1, rate=64000): self.CHUNK = chunk self.FORMAT = pyaudio.paInt16 self.CHANNELS = channels self.RATE = rate self._running = True self._frames = [] def start(self): threading._start_new_thread(self.__recording, ()) def __recording(self): self._running = True self._frames = [] p = pyaudio.PyAudio() stream = p.open(format=self.FORMAT, channels=self.CHANNELS, rate=self.RATE, input=True, frames_per_buffer=self.CHUNK) while(self._running): data = stream.read(self.CHUNK) self._frames.append(data) stream.stop_stream() stream.close() p.terminate() def stop(self): self._running = False def save(self, filename): p = pyaudio.PyAudio() if not filename.endswith(".wav"): filename = filename + ".wav" wf = wave.open(filename, 'wb') wf.setnchannels(self.CHANNELS) wf.setsampwidth(p.get_sample_size(self.FORMAT)) wf.setframerate(self.RATE) wf.writeframes(b''.join(self._frames)) wf.close() print("Saved") if __name__ == "__main__": for i in range(1,4): a = int(input('請輸入相應數字開始:')) if a == 1: rec = Recorder() begin = time.time() print("Start recording") rec.start() b = int(input('請輸入相應數字停止:')) if b == 2: print("Stop recording") rec.stop() fina = time.time() t = fina - begin print('錄音時間為%ds'%t) rec.save("1_%d.wav"%i)
上述就是小編為大家分享的使用python實現錄音功能并可隨時停止錄音了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。