python录音代码_python录音文件(别人的代码自己修改)

import tkinter

from tkinter import *

from tkinter import ttk

import os

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")

def startad():

global rec

rec = Recorder()

begin = time.time()

print("Start recording")

rec.start()

def stopad():

print("Stop recording")

rec.stop()

fina = time.time()

def savead():

rec.save("1.wav")

root=Tk()

Button1=tkinter.Button(root, text ="开始录音", command =startad)

Button1.grid(row=0,column=0,padx=20,pady=20)

Button2=tkinter.Button(root, text ="结束录音", command =stopad)

Button2.grid(row=0,column=1,padx=20,pady=20)

Button3=tkinter.Button(root, text ="保存录音", command = savead)

Button3.grid(row=0,column=2,padx=20,pady=20)

root.mainloop()

运行比较良好。能够把语音变成wav文件。

下一步准备整合成为傻瓜读书软件的一个部分。将偷懒进行到底。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值