记一次python处理音频

  1. 准备工作   安装pyaudio  以及ffmpeg 安装不上根据报错提示解决即可

直接上代码

# -- coding: utf-8 --
import threading
import time
import tkinter as tk
import pyaudio
import wave
import os
class TTTK:
    def __init__(self,init_tk):
        self.tk=init_tk
        print('init_tk',init_tk)
        init_tk.title('本地录音')
        init_tk.geometry('220x50')
        init_tk.resizable(0, 0)
        self.init_window()
        self.G=False

    def init_window(self):
        group1 = tk.Frame(self.tk,bd=1)  # , bg="green"
        group1.place(x=5, y=10, width=220, height=50)

        self.start = tk.Button(group1, text="录音", command=self.ly_start, width=8, anchor='center')
        self.start.grid(row=1, column=1, padx=10)

        self.stop = tk.Button(group1, text="停止", command=self.ly_stop, width=8, anchor='center')
        self.stop.grid(row=1, column=2, padx=20)

    def ly_start(self):
        self.G = False
        print('开始')
        t=threading.Thread(target=self.luyin,)
        t.setDaemon(True)
        t.start()
        self.start.config(state='disabled')
        self.stop.config(state='normal')


        # t.join()
        # self.luyin()

    def ly_stop(self):
        self.G=True
        print('停止并保存')
        self.stop.config(state='disabled')
        self.start.config(state='normal')


    def luyin(self):
        g_path=os.getcwd()
        CHUNK = 1024
        FORMAT = pyaudio.paInt16
        CHANNELS = 2
        RATE = 44100
        RECORD_SECONDS = 5
        t=time.strftime('%Y%m%d%H%M%S')
        full_filename=os.path.join(g_path,f"{t}--output.wav")
        WAVE_OUTPUT_FILENAME = full_filename
        p = pyaudio.PyAudio()
        stream = p.open(format=FORMAT,
                        channels=CHANNELS,
                        rate=RATE,
                        input=True,
                        frames_per_buffer=CHUNK)
        print("* recording")
        frames = []
        sc = 0
        # esc = int(RATE / CHUNK * RECORD_SECONDS)
        while True:
            sc += 1
            data = stream.read(CHUNK)
            frames.append(data)
            if self.G:
                break
        print("* done recording")
        stream.stop_stream()
        stream.close()
        p.terminate()
        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()
        time.sleep(1)
        os.system(f'ffmpeg -i "{full_filename}" -b:a 64k -acodec mp3 -ar 44100 -ac 1 "{t}.mp3"')
        os.remove(full_filename)




window=tk.Tk()
t=TTTK(window)

window.mainloop()

代码很简单,需要的拿去改一改就行了

 

搜索