faster_whisper语音识别

faster_whisper语音识别

检测可用设备:list_available_devices()函数

我这边usb摄像头带麦克风的,所以 DEV_index = 8

1 使用 pyaudio 打开音频设备

2 从音频设备读取数据,传递给 faster_whisper 识别

按键 r 录制 s 停止 q退出

test.py

python 复制代码
# from faster_whisper import WhisperModel

# model = WhisperModel("large-v3")

# audio_path= "mlk.flac"

# segments, info = model.transcribe(audio_path)

# for segment in segments:
#         print("[%.2fs -> %.2fs] %s" % (segment.start, segment.end, segment.text))



from faster_whisper import WhisperModel
import numpy as np
import keyboard
import pynput
from pynput.keyboard import Controller, Listener,Key,KeyCode
import time
import pyaudio
import wave

def list_available_devices():
    print("Available input devices:")
    p = pyaudio.PyAudio()
    for i in range(p.get_device_count()):
        device_info = p.get_device_info_by_index(i)
        if device_info['maxInputChannels'] > 0:  # Check if it's an input device
            print(f"{i}: {device_info['name']}")
    p.terminate()


# List available devices
list_available_devices()


# Available input devices:
# 5: USB Audio: #1 (hw:2,1)
# 6: USB Audio: #2 (hw:2,2)
# 8: aoni webcam A20: USB Audio (hw:3,0)
# 9: pulse
# 10: default

# Replace with the device index you identified by run list_available_devices()
DEV_index = 8  # Replace with your actual device index


class VoiceRecorder:
    def __init__(self, channels=1, rate=16000, format=pyaudio.paInt16):
        self.p = pyaudio.PyAudio()
        self.model = WhisperModel("large-v3")
        self.CHANNELS = channels
        self.RATE = rate
        self.FORMAT = format

    def record(self, seconds=5):
        """
        记录指定秒数的音频。
        """
        CHUNK = 1024
        
        try:
            stream = self.p.open(format=self.FORMAT,
                                channels=self.CHANNELS,
                                rate=self.RATE,
                                input=True,
                                input_device_index=DEV_index,
                                frames_per_buffer=CHUNK)
            print("开始录音...")
            frames = []
            
            for i in range(0, int(self.RATE / CHUNK * seconds)):
                data = stream.read(CHUNK)
                frames.append(data)
                
            print("录音结束.")
        except Exception as e:
            print(f"录音时发生错误:{e}")
            return None
        finally:
            stream.stop_stream()
            stream.close()
        
        return b''.join(frames)

    def transcribe_audio(self, audio_data):
        """
        将音频数据转换为文本。
        """
        try:
            audio_np = np.frombuffer(audio_data, dtype=np.int16)
            if self.CHANNELS > 1:
                audio_np = audio_np.reshape((-1, self.CHANNELS)).mean(axis=1)
            audio_normalized = np.float32(audio_np) / 32768.0
            
            segments, _ = self.model.transcribe(audio_normalized, language='zh', beam_size=5)
            return [segment.text for segment in segments]
        except Exception as e:
            print(f"转录音频时发生错误:{e}")
            return None

    def close(self):
        """
        关闭PyAudio。
        """
        self.p.terminate()

def main():
    global recorder
    global listener
    recorder = VoiceRecorder()

    listener = Listener(
        on_press=on_press
    )
    listener.start()
    listener.join()


def on_press(key:KeyCode):
    print(type(key))
    if key.char == 'r':
        print("开始录音...")
        audio_data = recorder.record()
        if audio_data is not None:
            transcripts = recorder.transcribe_audio(audio_data)
            for text in transcripts:
                print(text)
            print("录音结束.")
    elif key.char == 's':
        print("停止录音.")
    elif key.char == 'q':
        print("退出程序.")
        listener.stop()
        recorder.close()

if __name__ == "__main__":
    main()
相关推荐
时代文章11 小时前
GPT-SoVITS 模型测试笔记
笔记·gpt·语音识别
七月稻草人11 小时前
用30秒声音复刻自己的音色:Index-TTS远程部署与公网访问实践
人工智能·语音识别
小鹿研究点东西1 天前
直播带货长视频AI自动剪辑开播:一场直播如何反复利用?
ffmpeg·自动化·音视频·语音识别
俊基科技1 天前
智慧矿山通信升级:AP-0316 语音处理模组破解矿井对讲降噪、回声与远场拾音难题
语音识别·硬件开发·ai降噪·智慧矿山·回音消除·矿场通信
蓝桉~MLGT1 天前
语音陪伴助手
人工智能·语音识别
localbob1 天前
日语视频 SRT 字幕生成软件下载:日语视频本地自动翻译SRT字幕生成、日语视频自动翻译 Faster Whisper v1.7 下载与使用教程(含AMD显卡支持)
whisper·音视频·机器翻译·日语字幕翻译·日语视频翻译·本地ai翻译日语视频
雲明1 天前
Qwen2.5-7B-Instruct实战教程:Chainlit集成语音输入(Whisper API)
语音识别·大语言模型·qwen·chainlit
挂科边缘1 天前
手把手教你使用 Faster-Whisper 实时语音输入转文本,本地部署教程
人工智能·语言模型·whisper·faster-whisper·实时语音输入转文本
逗逗班学Python1 天前
基于 Faster-Whisper 的本地语音转字幕与会议纪要系统:从音频转写到 SRT 字幕与 Markdown 纪要完整项目实战
python·语音识别·faster-whisper·字幕生成·会议纪要
三千军1 天前
Buzz语音转文字离线免费版安装使用(含Whisper最新模型)
whisper·免费·语音转文字·离线·buzz