python實(shí)現(xiàn)錄音功能(可隨時(shí)停止錄音)
本文實(shí)例為大家分享了python實(shí)現(xiàn)錄音功能的具體代碼,供大家參考,具體內(nèi)容如下
# -*- coding: utf-8 -*- import pyaudioimport timeimport threadingimport 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(’請(qǐng)輸入相應(yīng)數(shù)字開始:’)) if a == 1: rec = Recorder() begin = time.time() print('Start recording') rec.start() b = int(input(’請(qǐng)輸入相應(yīng)數(shù)字停止:’)) if b == 2:print('Stop recording')rec.stop()fina = time.time()t = fina - beginprint(’錄音時(shí)間為%ds’%t)rec.save('1_%d.wav'%i)
本人在嘗試語音識(shí)別領(lǐng)域的研究,歡迎一起探討。
更多精彩python學(xué)習(xí)專題歡迎點(diǎn)擊學(xué)習(xí):
python入門基礎(chǔ)教程
python圖片處理操作匯總
python各版本安裝教程
python書單推薦 編程必備書單
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. React+umi+typeScript創(chuàng)建項(xiàng)目的過程2. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp3. php測(cè)試程序運(yùn)行速度和頁面執(zhí)行速度的代碼4. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究5. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析6. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁7. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報(bào)錯(cuò)問題分析8. ASP中常用的22個(gè)FSO文件操作函數(shù)整理9. SharePoint Server 2019新特性介紹10. 三個(gè)不常見的 HTML5 實(shí)用新特性簡(jiǎn)介
