本文介紹Paraformer即時語音辨識Python SDK的參數和介面細節。
重要本文檔僅適用於華北2(北京)地區。如需使用模型,需使用華北2(北京)地區的API Key。
重要阿里雲百鍊為華北2(北京)地區推出了業務空間專屬網域名稱,能夠為推理請求提供卓越的效能和更高的穩定性,建議從 dashscope.aliyuncs.com 遷移至 {WorkspaceId}.cn-beijing.maas.aliyuncs.com。
{WorkspaceId}需要替換為真實的Workspace ID。現有網域名稱仍可正常使用。
使用者指南:關於模型介紹和選型建議請參見即時語音辨識-Fun-ASR/Paraformer。
前提條件
已開通服務並擷取與配置 API Key。請配置API Key到環境變數,而非寫入程式碼在代碼中,防範因代碼泄露導致的安全風險。
說明當您需要為第三方應用或使用者提供臨時存取權限,或者希望嚴格控制敏感性資料訪問、刪除等高風險操作時,建議使用臨時鑒權Token。
與長期有效 API Key 相比,臨時鑒權 Token 具備時效性短(60秒)、安全性高的特點,適用於臨時調用情境,能有效降低API Key泄露的風險。
使用方式:在代碼中,將原本用於鑒權的 API Key 替換為擷取到的臨時鑒權 Token 即可。
模型列表
| paraformer-realtime-v2 | paraformer-realtime-8k-v2 | |
|---|---|---|
| 適用情境 | 直播、會議等情境 | 電話客服、語音信箱等 8kHz 音訊識別情境 |
| 採樣率 | 任意 | 8kHz |
| 語種 | 中文(包含中文普通話和各種方言)、英文、日語、韓語、德語、法語、俄語 支援的中文方言:上海話、吳語、閩南語、東北話、甘肅話、貴州話、河南話、湖北話、湖南話、江西話、寧夏話、山西話、陝西話、山東話、四川話、天津話、雲南話、粵語 | 中文 |
| 標點符號預測 | ✅ 預設支援,無需配置 | ✅ 預設支援,無需配置 |
| 逆文本正則化(ITN) | ✅ 預設支援,無需配置 | ✅ 預設支援,無需配置 |
| 定製熱詞 | ✅ 參見定製熱詞 | ✅ 參見定製熱詞 |
| 指定待識別語種 | ✅ 通過 | ❌ |
| 情感識別 | ❌ | ✅ (點擊查看使用方式) 情感識別遵循如下約束:
情感識別結果擷取方式:通過單句資訊(Sentence)的 |
快速開始
Recognition類提供了非流式調用和雙向流式調用介面。請根據實際需求選擇合適的調用方式:
- 非流式調用:針對本地檔案進行識別,並一次性返回完整的處理結果。適合處理錄製好的音頻。
- 雙向流式調用:可直接對音頻流進行識別,並即時輸出結果。音頻流可以來自外部裝置(如麥克風)或從本地檔案讀取。適合需要即時反饋的情境。
非流式調用
提交單個語音即時轉寫任務,通過傳入本地檔案的方式同步阻塞地拿到轉寫結果。
執行個體化Recognition類綁定請求參數,調用call進行識別/翻譯並最終擷取識別結果(RecognitionResult)。
點擊查看完整樣本
from http import HTTPStatus
from dashscope.audio.asr import Recognition
# 以下為華北2(北京)地區的配置,調用時請將"{WorkspaceId}"替換為真實的業務空間ID,各地區的配置不同。
dashscope.base_websocket_api_url = "wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference"
# 若沒有將API Key配置到環境變數中,需將下面這行代碼注釋放開,並將apiKey替換為自己的API Key
# import dashscope
# dashscope.api_key = "apiKey"
recognition = Recognition(model='paraformer-realtime-v2',
format='wav',
sample_rate=16000,
# “language_hints”只支援paraformer-realtime-v2模型
language_hints=['zh', 'en'],
callback=None)
result = recognition.call('{YOUR_AUDIO_FILE}')
if result.status_code == HTTPStatus.OK:
print('識別結果:')
sentences = result.get_sentence()
for sentence in sentences:
print(sentence['text'])
else:
print('Error: ', result.message)
print(
'[Metric] requestId: {}, first package delay ms: {}, last package delay ms: {}'
.format(
recognition.get_last_request_id(),
recognition.get_first_package_delay(),
recognition.get_last_package_delay(),
))
result.get_sentence()在非流式調用(call)中返回句子列表(List[Dict]),每個元素為Dict[str, Any],包含text(識別文本)、begin_time / end_time(時間戳記)、words(字時間戳記)等欄位。如需擷取識別文本,需遍曆列表並通過sentence['text']提取。
在流式回調(on_event)中,result.get_sentence()返回單句資訊(Dict[str, Any]),可直接使用sentence['text']擷取識別文本。兩種調用模式的傳回值類型不同,詳見識別結果(RecognitionResult)中的get_sentence方法說明。
雙向流式調用
提交單個語音即時轉寫任務,通過實現回調介面的方式流式輸出即時識別結果。
-
啟動流式語音辨識
執行個體化Recognition類綁定請求參數和回調介面(RecognitionCallback),調用
start方法啟動流式語音辨識。 -
串流
迴圈調用Recognition類的
send_audio_frame方法,將從本地檔案或裝置(如麥克風)讀取的二進位音頻流分段發送至服務端。在發送音頻資料的過程中,服務端會通過回調介面(RecognitionCallback)的
on_event方法,將識別結果即時返回給用戶端。建議每次發送的音頻時間長度約為100毫秒,資料大小保持在1KB至16KB之間。
-
結束處理
調用Recognition類的
stop方法結束語音辨識。該方法會阻塞當前線程,直到回調介面(RecognitionCallback)的
on_complete或者on_error回調觸發後才會釋放線程阻塞。
點擊查看完整樣本
import os
import signal # for keyboard events handling (press "Ctrl+C" to terminate recording)
import sys
import dashscope
import pyaudio
from dashscope.audio.asr import *
# 以下為華北2(北京)地區的配置,調用時請將"{WorkspaceId}"替換為真實的業務空間ID,各地區的配置不同。
dashscope.base_websocket_api_url = "wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference"
mic = None
stream = None
# Set recording parameters
sample_rate = 16000 # sampling rate (Hz)
channels = 1 # mono channel
dtype = 'int16' # data type
format_pcm = 'pcm' # the format of the audio data
block_size = 3200 # number of frames per buffer
def init_dashscope_api_key():
"""
Set your DashScope API-key. More information:
https://github.com/aliyun/alibabacloud-bailian-speech-demo/blob/master/PREREQUISITES.md
"""
if 'DASHSCOPE_API_KEY' in os.environ:
dashscope.api_key = os.environ[
'DASHSCOPE_API_KEY'] # load API-key from environment variable DASHSCOPE_API_KEY
else:
dashscope.api_key = '<your-dashscope-api-key>' # set API-key manually
# Real-time speech recognition callback
class Callback(RecognitionCallback):
def on_open(self) -> None:
global mic
global stream
print('RecognitionCallback open.')
mic = pyaudio.PyAudio()
stream = mic.open(format=pyaudio.paInt16,
channels=1,
rate=16000,
input=True)
def on_close(self) -> None:
global mic
global stream
print('RecognitionCallback close.')
stream.stop_stream()
stream.close()
mic.terminate()
stream = None
mic = None
def on_complete(self) -> None:
print('RecognitionCallback completed.') # recognition completed
def on_error(self, message) -> None:
print('RecognitionCallback task_id: ', message.request_id)
print('RecognitionCallback error: ', message.message)
# Stop and close the audio stream if it is running
if 'stream' in globals() and stream.active:
stream.stop()
stream.close()
# Forcefully exit the program
sys.exit(1)
def on_event(self, result: RecognitionResult) -> None:
sentence = result.get_sentence()
if 'text' in sentence:
print('RecognitionCallback text: ', sentence['text'])
if RecognitionResult.is_sentence_end(sentence):
print(
'RecognitionCallback sentence end, request_id:%s, usage:%s'
% (result.get_request_id(), result.get_usage(sentence)))
def signal_handler(sig, frame):
print('Ctrl+C pressed, stop recognition ...')
# Stop recognition
recognition.stop()
print('Recognition stopped.')
print(
'[Metric] requestId: {}, first package delay ms: {}, last package delay ms: {}'
.format(
recognition.get_last_request_id(),
recognition.get_first_package_delay(),
recognition.get_last_package_delay(),
))
# Forcefully exit the program
sys.exit(0)
# main function
if __name__ == '__main__':
init_dashscope_api_key()
print('Initializing ...')
# Create the recognition callback
callback = Callback()
# Call recognition service by async mode, you can customize the recognition parameters, like model, format,
# sample_rate
recognition = Recognition(
model='paraformer-realtime-v2',
format=format_pcm,
# 'pcm'、'wav'、'opus'、'speex'、'aac'、'amr', you can check the supported formats in the document
sample_rate=sample_rate,
# support 8000, 16000
semantic_punctuation_enabled=False,
callback=callback)
# Start recognition
recognition.start()
signal.signal(signal.SIGINT, signal_handler)
print("Press 'Ctrl+C' to stop recording and recognition...")
# Create a keyboard listener until "Ctrl+C" is pressed
while True:
if stream:
data = stream.read(3200, exception_on_overflow=False)
recognition.send_audio_frame(data)
else:
break
recognition.stop()
import os
import time
from dashscope.audio.asr import *
# 以下為華北2(北京)地區的配置,調用時請將"{WorkspaceId}"替換為真實的業務空間ID,各地區的配置不同。
dashscope.base_websocket_api_url = "wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference"
# 若沒有將API Key配置到環境變數中,需將下面這行代碼注釋放開,並將apiKey替換為自己的API Key
# import dashscope
# dashscope.api_key = "apiKey"
from datetime import datetime
def get_timestamp():
now = datetime.now()
formatted_timestamp = now.strftime("[%Y-%m-%d %H:%M:%S.%f]")
return formatted_timestamp
class Callback(RecognitionCallback):
def on_complete(self) -> None:
print(get_timestamp() + ' Recognition completed') # recognition complete
def on_error(self, result: RecognitionResult) -> None:
print('Recognition task_id: ', result.request_id)
print('Recognition error: ', result.message)
exit(0)
def on_event(self, result: RecognitionResult) -> None:
sentence = result.get_sentence()
if 'text' in sentence:
print(get_timestamp() + ' RecognitionCallback text: ', sentence['text'])
if RecognitionResult.is_sentence_end(sentence):
print(get_timestamp() +
'RecognitionCallback sentence end, request_id:%s, usage:%s'
% (result.get_request_id(), result.get_usage(sentence)))
callback = Callback()
recognition = Recognition(model='paraformer-realtime-v2',
format='wav',
sample_rate=16000,
# “language_hints”只支援paraformer-realtime-v2模型
language_hints=['zh', 'en'],
callback=callback)
recognition.start()
try:
audio_data: bytes = None
f = open("{YOUR_AUDIO_FILE}", 'rb')
if os.path.getsize("{YOUR_AUDIO_FILE}"):
while True:
audio_data = f.read(3200)
if not audio_data:
break
else:
recognition.send_audio_frame(audio_data)
time.sleep(0.1)
else:
raise Exception(
'The supplied file was empty (zero bytes long)')
f.close()
except Exception as e:
raise e
recognition.stop()
print(
'[Metric] requestId: {}, first package delay ms: {}, last package delay ms: {}'
.format(
recognition.get_last_request_id(),
recognition.get_first_package_delay(),
recognition.get_last_package_delay(),
))
並發調用
在Python中,由於存在全域解譯器鎖,同一時刻只有一個線程可以執行Python代碼(雖然某些效能導向的庫可能會去除此限制)。如果您想更好地利用多核心電腦的計算資源,推薦您使用multiprocessing或concurrent.futures.ProcessPoolExecutor。 多線程在較高並發下會顯著增加SDK調用延遲。
請求參數
請求參數通過Recognition類的構造方法(init)進行設定。
參數 | 類型 | 預設值 | 是否必須 | 說明 |
|---|---|---|---|---|
model | str | - | 是 | 用於即時語音辨識的模型(參見模型列表)。 |
sample_rate | int | - | 是 | 設定待識別音頻採樣率(單位Hz)。 因模型而異:
|
format | str | - | 是 | 設定待識別音頻格式。 支援的音頻格式:pcm、wav、mp3、opus、speex、aac、amr。 opus/speex:必須使用Ogg封裝; wav:必須為PCM編碼; amr:僅支援AMR-NB類型。 |
vocabulary_id | str | - | 否 | 設定熱詞ID,若未設定則不生效。v2及更高版本模型設定熱詞ID時使用該欄位。 在本次語音辨識中,將應用與該熱詞ID對應的熱詞資訊。具體使用方法請參見定製熱詞。 |
disfluency_removal_enabled | bool | False | 否 | 設定是否過濾語氣詞:
|
language_hints | list[str] | ["zh", "en"] | 否 | 設定待識別語言代碼。如果無法提前確定語種,可不設定,模型會自動識別語種。 目前支援的語言代碼:
該參數僅對支援多語言的模型生效(參見模型列表)。 |
semantic_punctuation_enabled | bool | False | 否 | 設定是否開啟語義斷句,預設關閉。
語義斷句準確性更高,適合會議轉寫情境;VAD(Voice Activity Detection,語音活動檢測)斷句延遲較低,適合互動情境。 通過調整 該參數僅在模型為v2及更高版本時生效。 |
max_sentence_silence | int | 800 | 否 | 設定VAD(Voice Activity Detection,語音活動檢測)斷句的靜音時間長度閾值(單位為ms)。 當一段語音後的靜音時間長度超過該閾值時,系統會判定該句子已結束。 參數範圍為200ms至6000ms,預設值為800ms。 該參數僅在 |
multi_threshold_mode_enabled | bool | False | 否 | 該開關開啟時(true)可以防止VAD斷句切割過長。預設關閉。 該參數僅在 |
punctuation_prediction_enabled | bool | True | 否 | 設定是否在識別結果中自動添加標點:
該參數僅在模型為v2及更高版本時生效。 |
heartbeat | bool | False | 否 | 當需要與服務端保持長串連時,可通過該開關進行控制:
該參數僅在模型為v2及更高版本時生效。 使用該欄位時,SDK版本不能低於1.23.1。 |
inverse_text_normalization_enabled | bool | True | 否 | 設定是否開啟ITN(Inverse Text Normalization,逆文本正則化)。 預設開啟(true)。開啟後,中文數字將轉換為阿拉伯數字。 該參數僅在模型為v2及更高版本時生效。 |
callback | RecognitionCallback | - | 否 |
關鍵介面
Recognition類
Recognition通過“from dashscope.audio.asr import *”方式引入。
| 成員方法 | 方法簽名 | 說明 |
|---|---|---|
call | | 基於本地檔案的非流式調用,該方法會阻塞當前線程直到全部音頻讀完,該方法要求所識別檔案具有可讀許可權。 識別結果以 |
start | | 開始語音辨識。 基於回調形式的流式即時識別,該方法不會阻塞當前線程。需要配合 |
send_audio_frame | | 推送音頻。每次推送的音頻流不宜過大或過小,建議每包音頻時間長度為100ms左右,大小在1KB~16KB之間。 識別結果通過回調介面(RecognitionCallback)的on_event方法擷取。 |
stop | | 停止語音辨識,阻塞到服務將收到的音頻都識別後結束任務。 |
get_last_request_id | | 擷取request_id,在建構函式調用(建立對象)後可以使用。 |
get_first_package_delay | | 擷取首包延遲,從發送第一包音頻到收到首包識別結果延遲,在任務完成後使用。 |
get_last_package_delay | | 獲得尾包延遲,發送 |
回調介面(RecognitionCallback)
雙向流式調用時,服務端會通過回調的方式,將關鍵流程資訊和資料返回給用戶端。您需要實現回調方法,處理服務端返回的資訊或者資料。
點擊查看樣本
class Callback(RecognitionCallback):
def on_open(self) -> None:
print('串連成功')
def on_event(self, result: RecognitionResult) -> None:
# 實現接收識別結果的邏輯
pass
def on_complete(self) -> None:
print('任務完成')
def on_error(self, result: RecognitionResult) -> None:
print('出現異常:', result)
def on_close(self) -> None:
print('串連關閉')
callback = Callback()
| 方法 | 參數 | 傳回值 | 描述 |
|---|---|---|---|
| 無 | 無 | 當和服務端建立串連完成後,該方法立刻被回調。 |
|
| 無 | 當服務有回複時會被回調。 |
| 無 | 無 | 當所有識別結果全部返回後進行回調。 |
|
| 無 | 發生異常時該方法被回調。 |
| 無 | 無 | 當服務已經關閉串連後進行回調。 |
響應結果
識別結果(RecognitionResult)
RecognitionResult代表雙向流式調用中一次即時識別或非流式調用的識別結果。
| 成員方法 | 方法簽名 | 說明 |
|---|---|---|
get_sentence | | 擷取當前識別的句子及時間戳記資訊。回調中返回的是單句資訊,所以此方法傳回型別為Dict[str, Any]。 詳情請參見單句資訊(Sentence)。 |
get_request_id | | 擷取請求的request_id。 |
is_sentence_end | | 判斷給定句子是否已經結束。 |
單句資訊(Sentence)
Sentence類成員如下:
參數 | 類型 | 說明 |
|---|---|---|
begin_time | int | 句子開始時間,單位為ms。 |
end_time | int | 句子結束時間,單位為ms。 |
text | str | 識別文本。 |
words | 字時間戳記資訊(Word)的list集合 | 字時間戳記資訊。 |
emo_tag | str | 當前句子的情感:
情感識別遵循如下約束:
|
emo_confidence | float | 當前句子識別情感的信賴度,取值範圍:[0.0,1.0]。值越大表示信賴度越高。 情感識別遵循如下約束:
|
字時間戳記資訊(Word)
Word類成員如下:
參數 | 類型 | 說明 |
|---|---|---|
begin_time | int | 字開始時間,單位為ms。 |
end_time | int | 字結束時間,單位為ms。 |
text | str | 字。 |
punctuation | str | 標點。 |
錯誤碼
如遇報錯問題,請參見錯誤碼進行排查。
若問題仍未解決,請加入開發人員群反饋遇到的問題,並提供Request ID,以便進一步排查問題。
更多樣本
更多樣本,請參見GitHub。
常見問題
功能特性
Q:在長時間靜默的情況下,如何保持與服務端長串連?
將請求參數heartbeat設定為true,並持續向服務端發送靜音音頻。
靜音音頻指的是在音頻檔案或資料流中沒有聲音訊號的內容。靜音音頻可以通過多種方法產生,例如使用音頻編輯軟體如Audacity或Adobe Audition,或者通過命令列工具如FFmpeg。
Q:如何將音頻格式轉換為滿足要求的格式?
可使用FFmpeg工具,更多用法請參見FFmpeg官網。
# 基礎轉換命令(萬能模板)
# -i,作用:輸入檔案路徑,常用值樣本:audio.wav
# -c:a,作用:音頻編碼器,常用值樣本:aac, libmp3lame, pcm_s16le
# -b:a,作用:位元速率(音質控制),常用值樣本:192k, 320k
# -ar,作用:採樣率,常用值樣本:44100 (CD), 48000, 16000
# -ac,作用:聲道數,常用值樣本:1(單聲道), 2(立體聲)
# -y,作用:覆蓋已存在檔案(無需值)
ffmpeg -i input_audio.ext -c:a 編碼器名 -b:a 位元速率 -ar 採樣率 -ac 聲道數 output.ext
# 例如:WAV → MP3(保持原始品質)
ffmpeg -i input.wav -c:a libmp3lame -q:a 0 output.mp3
# 例如:MP3 → WAV(16bit PCM標準格式)
ffmpeg -i input.mp3 -c:a pcm_s16le -ar 44100 -ac 2 output.wav
# 例如:M4A → AAC(提取/轉換蘋果音頻)
ffmpeg -i input.m4a -c:a copy output.aac # 直接提取不重編碼
ffmpeg -i input.m4a -c:a aac -b:a 256k output.aac # 重編碼提高品質
# 例如:FLAC無損 → Opus(高壓縮)
ffmpeg -i input.flac -c:a libopus -b:a 128k -vbr on output.opus
Q:是否支援查看每句話對應的時間範圍?
支援。語音辨識結果中會包含每句話的開始時間戳和結束時間戳記,可通過它們確定每句話的時間範圍。
Q:如何識別本地檔案(錄音檔案)?
識別本地檔案有兩種方式:
-
直接傳入本地檔案路徑:此種方式在最終識別結束後擷取完整識別結果,不適合即時反饋的情境。
參見非流式調用,在Recognition類的
call方法中傳入檔案路徑對錄音檔案直接進行識別。 -
將本地檔案轉成二進位流進行識別:此種方式一邊識別檔案一邊流式擷取識別結果,適合即時反饋的情境。
參見雙向流式調用,通過Recognition類的
send_audio_frame方法向服務端發送二進位流對其進行識別。
故障排查
Q:無法識別語音(無識別結果)是什麼原因?
-
請檢查請求參數中的音頻格式(
format)和採樣率(sampleRate/sample_rate)設定是否正確且符合參數約束。以下為常見錯誤樣本:- 音頻副檔名為 .wav,但實際為 MP3 格式,而請求參數
format設定為 mp3(參數設定錯誤)。 - 音頻採樣率為 3600Hz,但請求參數
sampleRate/sample_rate設定為 48000(參數設定錯誤)。
可以使用ffprobe工具擷取音訊容器、編碼、採樣率、聲道等資訊:
- 音頻副檔名為 .wav,但實際為 MP3 格式,而請求參數
ffprobe -v error -show_entries format=format_name -show_entries stream=codec_name,sample_rate,channels -of default=noprint_wrappers=1 input.xxx
-
使用
paraformer-realtime-v2模型時,請檢查language_hints設定的語言是否與音頻實際語言一致。例如:音頻實際為中文,但
language_hints設定為en(英文)。 -
若以上檢查均無問題,可通過定製熱詞提升對特定詞語的識別效果。
Q:音頻副檔名與實際編碼格式不一致導致無識別結果,如何處理?
當音頻檔案的副檔名與實際編碼格式不一致時(例如副檔名為.wav但實際編碼為 MP3),請求參數format必須與音訊實際編碼格式一致,而非副檔名。
您可以按以下步驟排查和解決:
- 檢查音頻實際格式:使用
ffprobe工具查看音頻檔案的實際編碼格式。
ffprobe -v error -show_entries format=format_name -show_entries stream=codec_name,sample_rate,channels -of default=noprint_wrappers=1 your_audio_file
- 轉換音頻格式:如果音訊實際編碼格式與目標格式不一致,可使用
ffmpeg工具將音頻轉換為標準 WAV 格式(PCM 編碼)。
ffmpeg -i input_file -c:a pcm_s16le -ar 16000 -ac 1 output.wav
- 修改請求參數:將
format參數設定為與轉換後音頻一致的格式(如wav),並確保sample_rate參數與音訊實際採樣率一致。
重要format參數設定為wav時,音頻必須為 PCM 編碼。如果音頻副檔名為.wav但實際編碼不是 PCM(例如 MP3),需要先使用上述ffmpeg命令進行格式轉換。