欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python使用whisper讀取藍(lán)牙耳機(jī)語音并轉(zhuǎn)為文字

 更新時(shí)間:2025年05月08日 09:15:15   作者:waterHBO  
這篇文章主要為大家詳細(xì)介紹了python如何使用whisper讀取藍(lán)牙耳機(jī)語音并識別轉(zhuǎn)為文字,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下

1. 起因目的

看到別人做了類似的效果。所以自己也想試試看。動(dòng)手。

2. 先看效果

3. 過程

我用的是藍(lán)牙耳機(jī),EDIFIER W820NB

先找到聲音,設(shè)置為 Hands-Free 模式

代碼 1 ,查找設(shè)備名稱, 看看哪個(gè)是能用的

我的設(shè)備, 能用的是 index=27

import sounddevice as sd
import numpy as np
import wave
import re

def list_input_devices():
    print("?? 可用音頻輸入設(shè)備列表:")
    input_devices = []
    devices = sd.query_devices()
    for i, device in enumerate(devices):
        if device['max_input_channels'] > 0:
            device['index'] = i
            print(f"Index {i}: {device['name']} - {device['max_input_channels']} channels - {device['default_samplerate']} Hz")
            input_devices.append(device)
    return input_devices

def record_audio(device_info, seconds=10):
    try:
        device_index = device_info['index']
        channels = 1  # 強(qiáng)制單聲道
        rate = 16000  # 強(qiáng)制 16000 Hz

        print(f"\n??? 使用設(shè)備: {device_info['name']}")
        print(f"?? 設(shè)備索引: {device_index}")
        print(f"?? 通道數(shù): {channels}")
        print(f"?? 采樣率: {rate} Hz\n")

        print("?? 檢查設(shè)備配置...")
        sd.check_input_settings(device=device_index, channels=channels, samplerate=rate, dtype='int16')
        print("? 配置有效")

        print("??? 正在錄音中...")
        audio_data = sd.rec(int(seconds * rate), samplerate=rate, channels=channels, dtype='int16', device=device_index)
        sd.wait()

        safe_device_name = re.sub(r'[^\w\s-]', '_', device_info['name']).replace('\r', '').replace('\n', '').strip()
        output_file = f"{safe_device_name}_output.wav"

        with wave.open(output_file, 'wb') as wf:
            wf.setnchannels(channels)
            wf.setsampwidth(2)
            wf.setframerate(rate)
            wf.writeframes(audio_data.tobytes())

        print(f"?? 錄音已保存為 {output_file}")

    except sd.PortAudioError as pae:
        print(f"? 音頻設(shè)備錯(cuò)誤:{pae}")
    except OSError as ose:
        print(f"? 文件系統(tǒng)錯(cuò)誤:{ose}")
    except Exception as e:
        print(f"? 未知錯(cuò)誤:{e}")

if __name__ == "__main__":
    print("?? 使用默認(rèn)音頻接口")
    input_devices = list_input_devices()
    if input_devices:
        for device in input_devices:
            if 'EDIFIER W820NB' in device['name'] and 'Hands-Free' in device['name']:
                print(f"正在測試耳機(jī)設(shè)備: {device['name']}")
                record_audio(device)
    else:
        print("? 沒有可用的音頻輸入設(shè)備。")

代碼 2 , 使用 whisper 轉(zhuǎn)為文字效果很勉強(qiáng),見文末總結(jié)。

import sounddevice as sd
import numpy as np
import wave
import tempfile
import os
import whisper

# 加載 Whisper 模型
model = whisper.load_model("medium")  # 可改為 "tiny", "base", "small", "large"

# 音頻錄制設(shè)置
CHANNELS = 1  # 單聲道,Hands-Free 模式通常只支持 1 通道
RATE = 16000  # 16000 Hz,適合 Hands-Free 模式
RECORD_SECONDS = 5  # 每次錄音時(shí)長(秒)
DEVICE_INDEX = 27  # 已驗(yàn)證可用的設(shè)備索引
DEVICE_NAME = "耳機(jī) (@System32\drivers\bthhfenum.sys,#2;%1 Hands-Free AG Audio%0;(EDIFIER W820NB 雙金標(biāo)版))"

def record_audio(seconds=RECORD_SECONDS):
    try:
        print(f"?? 正在錄音 {seconds} 秒...")
        # 使用 sounddevice 錄制音頻
        audio_data = sd.rec(
            int(seconds * RATE),
            samplerate=RATE,
            channels=CHANNELS,
            dtype='int16',
            device=DEVICE_INDEX
        )
        sd.wait()  # 等待錄音完成

        # 保存臨時(shí)音頻文件
        with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmpfile:
            with wave.open(tmpfile.name, 'wb') as wf:
                wf.setnchannels(CHANNELS)
                wf.setsampwidth(2)  # 16-bit 音頻
                wf.setframerate(RATE)
                wf.writeframes(audio_data.tobytes())
            return tmpfile.name

    except sd.PortAudioError as pae:
        print(f"? 音頻設(shè)備錯(cuò)誤:{pae}")
        return None
    except Exception as e:
        print(f"? 未知錯(cuò)誤:{e}")
        return None

def transcribe_audio(audio_file):
    try:
        print("?? 正在識別...")
        result = model.transcribe(audio_file, language="zh")
        print("?? 識別結(jié)果:", result['text'].strip())
    except Exception as e:
        print(f"? 語音識別失?。簕e}")
    finally:
        if os.path.exists(audio_file):
            os.remove(audio_file)

if __name__ == "__main__":
    print(f"?? 使用設(shè)備: {DEVICE_NAME} (索引: {DEVICE_INDEX})")
    print("??? 開始實(shí)時(shí)聽寫,按 Ctrl+C 停止")

    try:
        while True:
            # 錄制音頻
            audio_file = record_audio()
            if audio_file:
                # 進(jìn)行語音識別
                transcribe_audio(audio_file)
            else:
                print("?? 錄音失敗,跳過識別")
            # 短暫暫停,避免過于頻繁的錄音
            sd.sleep(100)  # 100 毫秒

    except KeyboardInterrupt:
        print("?? 停止實(shí)時(shí)識別")
    except Exception as e:
        print(f"? 程序錯(cuò)誤:{e}")

4. 結(jié)論 + todo

  • 開始的時(shí)候,加載模型比較慢。
  • 能實(shí)現(xiàn)實(shí)時(shí)語音識別,但識別效果不佳,我猜測的原因是:
  • 耳機(jī)質(zhì)量太差,有些參數(shù)設(shè)置不夠合理。

到此這篇關(guān)于python使用whisper讀取藍(lán)牙耳機(jī)語音并轉(zhuǎn)為文字的文章就介紹到這了,更多相關(guān)python whisper讀取藍(lán)牙耳機(jī)并轉(zhuǎn)文字內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python實(shí)現(xiàn)給微信公眾號發(fā)送消息的方法

    python實(shí)現(xiàn)給微信公眾號發(fā)送消息的方法

    這篇文章主要介紹了python實(shí)現(xiàn)給微信公眾號發(fā)送消息的方法,結(jié)合實(shí)例形式分析了Python針對微信公眾號接口操作的相關(guān)技巧,需要的朋友可以參考下
    2017-06-06
  • python進(jìn)程池的簡單實(shí)現(xiàn)

    python進(jìn)程池的簡單實(shí)現(xiàn)

    本文主要介紹了python進(jìn)程池的簡單實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • Python使用tkinter模塊實(shí)現(xiàn)GUI界面的學(xué)生信息管理系統(tǒng)流程分步詳解

    Python使用tkinter模塊實(shí)現(xiàn)GUI界面的學(xué)生信息管理系統(tǒng)流程分步詳解

    這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)簡易學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2023-01-01
  • 關(guān)于Python中的同步異步阻塞與非阻塞

    關(guān)于Python中的同步異步阻塞與非阻塞

    這篇文章主要介紹了關(guān)于Python中的同步異步阻塞與非阻塞,具有一定的參考價(jià)值,有需要的朋友可以看一下
    2023-03-03
  • Python中的yield淺析

    Python中的yield淺析

    這篇文章主要介紹了Python中的yield淺析,對迭代器(iterator) 、生成器(constructor)一并做了分析,并用實(shí)例來說明,需要的朋友可以參考下
    2014-06-06
  • Python圖像處理Pillow庫的安裝使用

    Python圖像處理Pillow庫的安裝使用

    本文詳細(xì)介紹了Python第三方庫Pillow的使用,通過導(dǎo)入Pillow庫、打開和保存圖像、基本圖像操作以及圖像處理高級功能的代碼示例,我們了解了Pillow庫的強(qiáng)大功能和靈活性,感興趣的朋友跟隨小編一起看看吧
    2023-07-07
  • 最新版 Windows10上安裝Python 3.8.5的步驟詳解

    最新版 Windows10上安裝Python 3.8.5的步驟詳解

    這篇文章主要介紹了最新版 Windows10上安裝Python 3.8.5的步驟詳解,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-11-11
  • pipreqs?./?--encoding=utf-8?--force?報(bào)錯(cuò)問題解決

    pipreqs?./?--encoding=utf-8?--force?報(bào)錯(cuò)問題解決

    本文主要介紹了pipreqs?./?--encoding=utf-8?--force?報(bào)錯(cuò)問題解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-04-04
  • Django的restframework接口框架自定義返回?cái)?shù)據(jù)格式的示例詳解

    Django的restframework接口框架自定義返回?cái)?shù)據(jù)格式的示例詳解

    這篇文章主要介紹了Django的restframework接口框架自定義返回?cái)?shù)據(jù)格式,本文介紹了通過Django的restframework接口框架自定義Response返回對象來自定義返回?cái)?shù)據(jù)格式,本文通過示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-07-07
  • Python實(shí)現(xiàn)的棧(Stack)

    Python實(shí)現(xiàn)的棧(Stack)

    棧作為一種數(shù)據(jù)結(jié)構(gòu),是一種只能在一端進(jìn)行插入和刪除操作。這篇文章給大家介紹了Python實(shí)現(xiàn)的棧(Stack)的相關(guān)資料,感興趣的朋友一起看看吧
    2018-01-01

最新評論