溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python調(diào)用百度api怎么實(shí)現(xiàn)語音識(shí)別

發(fā)布時(shí)間:2021-12-07 15:09:57 來源:億速云 閱讀:164 作者:柒染 欄目:開發(fā)技術(shù)

Python調(diào)用百度api怎么實(shí)現(xiàn)語音識(shí)別,相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

最近在學(xué)習(xí)python,做一些python練習(xí)題

github上幾年前的練習(xí)題

有一題是這樣的:

使用 Python 實(shí)現(xiàn):對著電腦吼一聲,自動(dòng)打開瀏覽器中的默認(rèn)網(wǎng)站。

例如,對著筆記本電腦吼一聲“百度”,瀏覽器自動(dòng)打開百度首頁。

然后開始search相應(yīng)的功能需要的模塊(windows10),理一下思路:

  1. 本地錄音

  2. 上傳錄音,獲得返回結(jié)果

  3. 組一個(gè)map,根據(jù)結(jié)果打開相應(yīng)的網(wǎng)頁

所需模塊:

  1. PyAudio:錄音接口

  2. wave:打開錄音文件并設(shè)置音頻參數(shù)

  3. requests:GET/POST

為什么要用百度語音識(shí)別api呢?因?yàn)槊赓M(fèi)試用。。

Python調(diào)用百度api怎么實(shí)現(xiàn)語音識(shí)別

不多說,登錄百度云,創(chuàng)建應(yīng)用

Python調(diào)用百度api怎么實(shí)現(xiàn)語音識(shí)別

簡單概括就是

1.可以下載使用SDK

Python調(diào)用百度api怎么實(shí)現(xiàn)語音識(shí)別

2.不需要下載使用SDK

選擇2.

  1. 根據(jù)文檔組裝url獲取token

  2. 處理本地音頻以JSON格式POST到百度語音識(shí)別服務(wù)器,獲得返回結(jié)果

語音格式

格式支持:pcm(不壓縮)、wav(不壓縮,pcm編碼)、amr(壓縮格式)。推薦pcm 采樣率 :16000 固定值。 編碼:16bit 位深的單聲道。

百度服務(wù)端會(huì)將非pcm格式,轉(zhuǎn)為pcm格式,因此使用wav、amr會(huì)有額外的轉(zhuǎn)換耗時(shí)。

保存為pcm格式可以識(shí)別,只是windows自帶播放器識(shí)別不了pcm格式的,所以改用wav格式,畢竟用的模塊是wave?

首先是本地錄音

import wave
from pyaudio import PyAudio, paInt16

framerate = 16000  # 采樣率
num_samples = 2000  # 采樣點(diǎn)
channels = 1  # 聲道
sampwidth = 2  # 采樣寬度2bytes
FILEPATH = 'speech.wav'

def save_wave_file(filepath, data):
    wf = wave.open(filepath, 'wb')
    wf.setnchannels(channels)
    wf.setsampwidth(sampwidth)
    wf.setframerate(framerate)
    wf.writeframes(b''.join(data))
    wf.close()

#錄音
def my_record():
    pa = PyAudio()
    #打開一個(gè)新的音頻stream
    stream = pa.open(format=paInt16, channels=channels,
                     rate=framerate, input=True, frames_per_buffer=num_samples)
    my_buf = [] #存放錄音數(shù)據(jù)

    t = time.time()
    print('正在錄音...')
 
    while time.time() < t + 4:  # 設(shè)置錄音時(shí)間(秒)
    	#循環(huán)read,每次read 2000frames
        string_audio_data = stream.read(num_samples)
        my_buf.append(string_audio_data)
    print('錄音結(jié)束.')
    save_wave_file(FILEPATH, my_buf)
    stream.close()

然后是獲取token

import requests
import base64 #百度語音要求對本地語音二進(jìn)制數(shù)據(jù)進(jìn)行base64編碼

#組裝url獲取token,詳見文檔
base_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s"
APIKey = "LZAdqHUGC********mbfKm"
SecretKey = "WYPPwgHu********BU6GM*****"

HOST = base_url % (APIKey, SecretKey)

def getToken(host):
    res = requests.post(host)
    return res.json()['access_token']



#傳入語音二進(jìn)制數(shù)據(jù),token
#dev_pid為百度語音識(shí)別提供的幾種語言選擇
def speech3text(speech_data, token, dev_pid=1537):
    FORMAT = 'wav'
    RATE = '16000'
    CHANNEL = 1
    CUID = '********'
    SPEECH = base64.b64encode(speech_data).decode('utf-8')

    data = {
        'format': FORMAT,
        'rate': RATE,
        'channel': CHANNEL,
        'cuid': CUID,
        'len': len(speech_data),
        'speech': SPEECH,
        'token': token,
        'dev_pid':dev_pid
    }
    url = 'https://vop.baidu.com/server_api'
    headers = {'Content-Type': 'application/json'}
    # r=requests.post(url,data=json.dumps(data),headers=headers)
    print('正在識(shí)別...')
    r = requests.post(url, json=data, headers=headers)
    Result = r.json()
    if 'result' in Result:
        return Result['result'][0]
    else:
        return Result

最后就是對返回的結(jié)果進(jìn)行匹配,這里使用webbrowser這個(gè)模塊

webbrower.open(url)

完整demo

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Date    : 2018-12-02 19:04:55
import wave
import requests
import time
import base64
from pyaudio import PyAudio, paInt16
import webbrowser


framerate = 16000  # 采樣率
num_samples = 2000  # 采樣點(diǎn)
channels = 1  # 聲道
sampwidth = 2  # 采樣寬度2bytes
FILEPATH = 'speech.wav'

base_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s"
APIKey = "********"
SecretKey = "************"

HOST = base_url % (APIKey, SecretKey)


def getToken(host):
    res = requests.post(host)
    return res.json()['access_token']


def save_wave_file(filepath, data):
    wf = wave.open(filepath, 'wb')
    wf.setnchannels(channels)
    wf.setsampwidth(sampwidth)
    wf.setframerate(framerate)
    wf.writeframes(b''.join(data))
    wf.close()


def my_record():
    pa = PyAudio()
    stream = pa.open(format=paInt16, channels=channels,
                     rate=framerate, input=True, frames_per_buffer=num_samples)
    my_buf = []
    # count = 0
    t = time.time()
    print('正在錄音...')
  
    while time.time() < t + 4:  # 秒
        string_audio_data = stream.read(num_samples)
        my_buf.append(string_audio_data)
    print('錄音結(jié)束.')
    save_wave_file(FILEPATH, my_buf)
    stream.close()


def get_audio(file):
    with open(file, 'rb') as f:
        data = f.read()
    return data


def speech3text(speech_data, token, dev_pid=1537):
    FORMAT = 'wav'
    RATE = '16000'
    CHANNEL = 1
    CUID = '*******'
    SPEECH = base64.b64encode(speech_data).decode('utf-8')

    data = {
        'format': FORMAT,
        'rate': RATE,
        'channel': CHANNEL,
        'cuid': CUID,
        'len': len(speech_data),
        'speech': SPEECH,
        'token': token,
        'dev_pid':dev_pid
    }
    url = 'https://vop.baidu.com/server_api'
    headers = {'Content-Type': 'application/json'}
    # r=requests.post(url,data=json.dumps(data),headers=headers)
    print('正在識(shí)別...')
    r = requests.post(url, json=data, headers=headers)
    Result = r.json()
    if 'result' in Result:
        return Result['result'][0]
    else:
        return Result


def openbrowser(text):
    maps = {
        '百度': ['百度', 'baidu'],
        '騰訊': ['騰訊', 'tengxun'],
        '網(wǎng)易': ['網(wǎng)易', 'wangyi']

    }
    if text in maps['百度']:
        webbrowser.open_new_tab('https://www.baidu.com')
    elif text in maps['騰訊']:
        webbrowser.open_new_tab('https://www.qq.com')
    elif text in maps['網(wǎng)易']:
        webbrowser.open_new_tab('https://www.163.com/')
    else:
        webbrowser.open_new_tab('https://www.baidu.com/s?wd=%s' % text)


if __name__ == '__main__':
    flag = 'y'
    while flag.lower() == 'y':
        print('請輸入數(shù)字選擇語言:')
        devpid = input('1536:普通話(簡單英文),1537:普通話(有標(biāo)點(diǎn)),1737:英語,1637:粵語,1837:四川話\n')
        my_record()
        TOKEN = getToken(HOST)
        speech = get_audio(FILEPATH)
        result = speech3text(speech, TOKEN, int(devpid))
        print(result)
        if type(result) == str:
            openbrowser(result.strip(','))
        flag = input('Continue?(y/n):')

經(jīng)測試,大吼效果更佳 。

看完上述內(nèi)容,你們掌握Python調(diào)用百度api怎么實(shí)現(xiàn)語音識(shí)別的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI