Python+PyQt5实现录放音

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Record.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


import sys
import os
import wave
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication
from PyQt5.Qt import *
from os import path, system, popen
from time import strftime, localtime, time
from sys import argv, exit
from pyaudio import PyAudio, paInt16
from threading import Thread


class Ui_MainWindow(object):
    def __init__(self):
        super(Ui_MainWindow,self).__init__()
        self.win=QMainWindow()
        self.setupUi(self.win)
        self.pause_flag = False
        self.ii=0
        self.timer=QTimer()
        #self.timer.start(1000)
        self.timer.timeout.connect(self.disciver)
        self.pbt_Record.clicked.connect(self.transcription)
        self.pbt_Play.clicked.connect(self.play_wav)

    def play_wav(self):
        self.pbt_Play.setEnabled(False)
        self.t_play=Thread(target=self.demo)
        self.t_play.start()

    def demo(self):
        if path.exists('./media'):
            self.pbt_Play.setText('播放中..')
            wav_file_path='./media/test.wav'
            wf=wave.open(wav_file_path)
            self.pa=PyAudio()
            stream = self.pa.open(format=self.pa.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(),
                              rate=wf.getframerate(), output=True)
            chunk = 1024
            print('开始播放')
            data = wf.readframes(chunk)
            while data != b'':
                stream.write(data)
                data = wf.readframes(chunk)
            print('播放完毕')
            # 播放完后将文件关闭
            wf.close()
            # 停止声卡
            stream.stop_stream()
            # 关闭声卡
            stream.close()
            # 终止pyaudio
            self.pa.terminate()
            self.pa = None
            self.pbt_Play.setEnabled(True)
            self.pbt_Play.setText('播放')
        else:
            self.pbt_Play.setEnabled(False)


    def setprogressBar(self,i):
        self.progressBar.setValue(i)

    def disciver(self):
        self.t_discover=Thread(target=self.show_time)
        self.t_discover.start()

    def show_time(self):
        if not path.exists('./media'):
            system('MD media')
        if self.progressBar.value()!=self.progressBar.maximum():
            self.ii+=10
            self.progressBar.setValue(self.ii)
        else:
            self.pbt_Play.setEnabled(True)
            self.pause_flag=True

    def transcription(self):
        self.ii=0
        self.pause_flag = False
        self.progressBar.setValue(0)
        self.pbt_Play.setEnabled(False)
        self.pbt_Record.setEnabled(False)
        self.timer.start(1000)
        self.t_record=Thread(target=self.record)
        self.t_record.start()

    def record(self):
        #os.remove('./media/' + strftime("test", localtime(time())) + '.wav')
        if os.path.exists('./media/test.wav'):
            os.remove('./media/test.wav')
        self.pbt_Record.setText('录制中..')
        # 创建PyAudio对象
        self.pa = PyAudio()
        # 打开声卡,设置 采样深度为16位、声道数为2、采样率为16、模式为输入、采样点缓存数量为2048
        stream = self.pa.open(format=paInt16, channels=2, rate=16000, input=True, frames_per_buffer=2048)
        # 新建一个列表,用来存储采样到的数据
        record_buf = []
        while True:
            if self.pause_flag is True:
                break
            audio_data = stream.read(2048)  # 读出声卡缓冲区的音频数据
            record_buf.append(audio_data)  # 将读出的音频数据追加到record_buf列表
        #my_path = './media/' + strftime("test", localtime(time())) + '.wav'
        my_path = './media/test.wav'
        wf = wave.open(my_path, 'wb')  # 创建一个音频文件
        wf.setnchannels(2)  # 设置声道数为2
        wf.setsampwidth(2)  # 设置采样深度为
        wf.setframerate(16000)  # 设置采样率为16000
        # 将数据写入创建的音频文件
        wf.writeframes("".encode().join(record_buf))
        # 写完后将文件关闭
        wf.close()
        # 停止声卡
        stream.stop_stream()
        # 关闭声卡
        stream.close()
        # 终止pyaudio
        self.pa.terminate()
        self.pa = None
        self.pbt_Record.setText('录制')
        self.pbt_Record.setEnabled(True)


    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(640, 303)
        MainWindow.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)#只显示最小化按钮和关闭按钮
        MainWindow.setFixedSize(self.win.width(),self.win.height())
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pbt_Record = QtWidgets.QPushButton(self.centralwidget)
        self.pbt_Record.setGeometry(QtCore.QRect(90, 170, 91, 31))
        self.pbt_Record.setObjectName("pbt_Record")
        self.pbt_Play = QtWidgets.QPushButton(self.centralwidget)
        self.pbt_Play.setGeometry(QtCore.QRect(390, 170, 91, 31))
        self.pbt_Play.setObjectName("pbt_Play")
        self.pbt_Play.setEnabled(False)
        self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
        self.progressBar.setGeometry(QtCore.QRect(20, 80, 601, 31))
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        MainWindow.show()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Record"))
        self.pbt_Record.setText(_translate("MainWindow", "录制"))
        self.pbt_Play.setText(_translate("MainWindow", "播放"))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = Ui_MainWindow()
    sys.exit(app.exec_())

 

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值