使用python实现录音功能并可随时停止录音

发布时间:2020-10-28 00:57:28 作者:Leah
来源:亿速云 阅读:375

这期内容当中小编将会给大家带来有关使用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实现录音功能并可随时停止录音了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. ios录音功能
  2. html5怎么实现手机触摸出现录音以及离开停止录音并上传的功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:php的配置文件是什么

下一篇:PHP的发展前景

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》