欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python实现录音功能(可随时停止录音)

程序员文章站 2022-06-22 09:37:00
本文实例为大家分享了python实现录音功能的具体代码,供大家参考,具体内容如下# -*- coding: utf-8 -*- import pyaudioimport timeimport thre...

本文实例为大家分享了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学习专题欢迎点击学习:

python入门基础教程

python图片处理操作汇总

python各版本安装教程

python书单推荐 编程必备书单

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

相关标签: python 录音