全部產品
Search
文件中心

Alibaba Cloud Model Studio:Qwen-Audio-ASR-Message Python SDK

更新時間:Nov 27, 2026

前提条件

API 端點 — Qwen-Audio-ASR-Message

SDK 中的即時辨識使用 WebSocket 介面,端點由 Client 的 workspace 和 region(包含 WorkspaceId)自動決定。如需切換至其他地域,請在建構 Client 時將 region 設定為對應地域。

新加坡

wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference

呼叫時請將 {WorkspaceId} 替換為您實際的 Workspace ID。

中國(北京)

wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference

呼叫時請將 {WorkspaceId} 替換為您實際的 Workspace ID。

日本(東京)

wss://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/api-ws/v1/inference

呼叫時請將 {WorkspaceId} 替換為您實際的 Workspace ID。

重要阿里雲 Model Studio 已為中國(北京)和新加坡地域推出業務空間專屬網域名稱,可為推理請求提供更優異的效能與更高的穩定性。我們建議您遷移至新網域名稱:

  • 中國(北京)地域:從 dashscope.aliyuncs.com 遷移至 {WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • 新加坡地域:從 dashscope-intl.aliyuncs.com 遷移至 {WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

快速開始

請將 {WorkspaceId} 替換為您的業務空間 ID,並將 {YOUR_AUDIO_FILE} 替換為本機 16 kHz WAV 檔案的路徑。範例會在終端機中列印轉寫結果。

import os
import dashscope

# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
    api_key=os.environ.get('DASHSCOPE_API_KEY'),
    # The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

# Recognize a local audio file: recognize_file automatically sends the audio in chunks and drives the task to completion
for event in client.audio.asr.recognize_file(
        '{YOUR_AUDIO_FILE}',
        model='qwen-audio-3.1-asr-flash-message',
        format='wav',
        sample_rate=16000):
    payload = event.get('payload') or {}
    sentence = (payload.get('output') or {}).get('sentence') or {}
    if sentence.get('text') and not sentence.get('heartbeat'):
        print('识别结果:', sentence['text'])

其他範例

以下呼叫範例為共用範例。請根據下表替換範例中的模型 ID。

模型範例中的模型 ID
Qwen-Audio-ASR-Streamingqwen-audio-3.1-asr-flash-streaming
麥克風範例使用 qwen-audio-3.0-asr-flash-streaming。
Qwen-Audio-ASR-Messageqwen-audio-3.1-asr-flash-message
僅支援 16000 Hz 取樣率。
Fun-ASR-Realtimefun-asr-realtime

核心資源 (client.audio.asr) 提供非串流呼叫與雙向串流呼叫等介面。請根據實際需求選擇合適的呼叫方式:

  • 非串流呼叫(recognize_file):對本機檔案執行辨識;SDK 會自動分段傳送音訊並驅動任務完成。適合處理錄製的音訊。
  • 雙向串流呼叫(recognize 工作階段):直接對音訊串流執行辨識並即時輸出結果。音訊串流可來自外部裝置(如麥克風)或從本機檔案讀取。適合需要即時回饋的情境。

非串流呼叫

透過傳入本機檔案,提交單一即時語音轉寫任務,並以阻塞方式同步取得轉寫結果。

呼叫 核心資源 (client.audio.asr) 的 recognize_file 方法以綁定請求參數並傳入本機檔案路徑,然後迭代伺服器端事件以取得辨識結果。

import os
import dashscope

# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
    api_key=os.environ.get('DASHSCOPE_API_KEY'),
    # The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

# Recognize a local audio file: recognize_file automatically sends the audio in chunks and drives the task to completion
for event in client.audio.asr.recognize_file(
        '{YOUR_AUDIO_FILE}',
        model='qwen-audio-3.1-asr-flash-streaming',
        format='wav',
        sample_rate=16000):
    payload = event.get('payload') or {}
    sentence = (payload.get('output') or {}).get('sentence') or {}
    if sentence.get('text') and not sentence.get('heartbeat'):
        print('识别结果:', sentence['text'])

雙向串流呼叫

提交單一即時語音轉寫任務,透過迭代事件串流輸出即時辨識結果。

  1. 開始串流語音辨識

    呼叫 核心資源 (client.audio.asr) 的 recognize 方法以建立辨識工作階段並綁定請求參數,接著進入 with 上下文(會自動呼叫 start 方法建立連線並傳送任務),開始串流語音辨識。

  2. 串流

    循環呼叫工作階段的 send_audio_frame 方法,將從本機檔案或裝置(如麥克風)讀取的二進位音訊串流分段傳送至伺服器。傳送與接收必須並行進行:接收執行緒透過工作階段的 events() 方法迭代伺服器端事件,並即時將辨識結果返回給用戶端。

    建議每次傳送的音訊長度約為 100 毫秒,資料大小保持在 1 KB 至 16 KB 之間。

  3. 結束處理

    呼叫 session 的 stop 方法結束語音辨識。

    此方法僅通知伺服器輸入已結束;接收執行緒必須繼續消費 events() 直到 task-finished 事件,才能取得最終辨識結果與統計資訊。ws 層的錯誤會以 DashScopeError 例外拋出,您可在傳送或接收處使用 try/except 捕捉。

import os
import signal  # for keyboard events handling (press "Ctrl+C" to terminate recording)
import sys

import dashscope
import pyaudio
from concurrent.futures import ThreadPoolExecutor

mic = None
stream = None

# Set recording parameters
sample_rate = 16000  # 麦克风与请求使用相同的采样率。Qwen-Audio-ASR-Message 仅支持 16000 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

# Real-time speech recognition event receiver
def receive_events(rec):
    for event in rec.events():
        payload = event.get('payload') or {}
        sentence = (payload.get('output') or {}).get('sentence') or {}
        if sentence.get('text') and not sentence.get('heartbeat'):
            print('Recognition text: ', sentence['text'])
            if sentence.get('sentence_end'):
                print(
                    'Recognition sentence end, request_id:%s, usage:%s'
                    % (rec.request_id, rec.usage))

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.request_id,
            recognition.first_package_delay,
            recognition.last_package_delay,
        ))
    # Forcefully exit the program
    sys.exit(0)

# main function
if __name__ == '__main__':
    # The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
    # If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
    client = dashscope.Client(
        api_key=os.environ.get('DASHSCOPE_API_KEY'),
        # The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
        workspace="{WorkspaceId}",
        region="ap-southeast-1",
    )

    # Call recognition service, you can customize the recognition parameters, like model, format,
    # sample_rate
    with client.audio.asr.recognize(
            model='qwen-audio-3.0-asr-flash-streaming',
            format=format_pcm,
            # 'pcm'、'wav'、'opus'、'speex'、'aac'、'amr', you can check the supported formats in the document
            sample_rate=sample_rate,
    ) as recognition:
        # Open the microphone
        mic = pyaudio.PyAudio()
        stream = mic.open(format=pyaudio.paInt16,
                          channels=1,
                          rate=sample_rate,
                          input=True)
        with ThreadPoolExecutor(max_workers=1) as pool:
            receiver = pool.submit(receive_events, recognition)
            try:
                # Send audio from the microphone until "Ctrl+C" is pressed
                while stream:
                    data = stream.read(3200, exception_on_overflow=False)
                    recognition.send_audio_frame(data)
                recognition.stop()
                receiver.result()
            finally:
                # close must run inside the pool context to unblock the receiver
                recognition.close()
        stream.stop_stream()
        stream.close()
        mic.terminate()
        stream = None
        mic = None
import os
import time
import dashscope
from concurrent.futures import ThreadPoolExecutor

# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
    api_key=os.environ.get('DASHSCOPE_API_KEY'),
    # The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

from datetime import datetime

def get_timestamp():
    now = datetime.now()
    formatted_timestamp = now.strftime("[%Y-%m-%d %H:%M:%S.%f]")
    return formatted_timestamp

# Real-time speech recognition event receiver
def receive_events(rec):
    for event in rec.events():
        payload = event.get('payload') or {}
        sentence = (payload.get('output') or {}).get('sentence') or {}
        if sentence.get('text') and not sentence.get('heartbeat'):
            print(get_timestamp() + ' Recognition text: ', sentence['text'])
        if sentence.get('sentence_end'):
            print(get_timestamp() +
                  'Recognition sentence end, request_id:%s, usage:%s'
                  % (rec.request_id, rec.usage))

with client.audio.asr.recognize(
        model='qwen-audio-3.1-asr-flash-streaming',
        format='wav',
        sample_rate=16000,
) as recognition:
    with ThreadPoolExecutor(max_workers=1) as pool:
        receiver = pool.submit(receive_events, recognition)
        try:
            audio_data: bytes = None
            f = open("{YOUR_AUDIO_FILE}", 'rb')
            if os.path.getsize("{YOUR_AUDIO_FILE}"):
                # Read all the file data into the buffer at once
                file_buffer = f.read()
                f.close()
                print("Start Recognition")

                # Send 3200 bytes from the buffer at a time
                buffer_size = len(file_buffer)
                offset = 0
                chunk_size = 3200

                while offset < buffer_size:
                    # Calculate the size of the data chunk to send this time
                    remaining_bytes = buffer_size - offset
                    current_chunk_size = min(chunk_size, remaining_bytes)

                    # Extract the current data chunk from the buffer
                    audio_data = file_buffer[offset:offset + current_chunk_size]

                    # Send the audio data frame
                    recognition.send_audio_frame(audio_data)
                    # Update the offset
                    offset += current_chunk_size

                    # Add a delay to simulate real-time transmission
                    time.sleep(0.1)

                recognition.stop()
                receiver.result()
            else:
                raise Exception(
                    'The supplied file was empty (zero bytes long)')
        finally:
            # close must run inside the pool context to unblock the receiver
            recognition.close()

print(
    '[Metric] requestId: {}, first package delay ms: {}, last package delay ms: {}'
    .format(
        recognition.request_id,
        recognition.first_package_delay,
        recognition.last_package_delay,
    ))

請求參數

Qwen-Audio-ASR-Message

共用說明

請參閱新版的 Qwen-Audio-ASR-Message Python SDK。

請求參數透過核心資源 (client.audio.asr)的 recognize/recognize_file 方法設定:model、format、sample_rate、vocabulary_id 可直接傳入;language_hints 則透過 parameters 字典傳入。

參數類型是否必填描述
modelstr是模型名稱,設為 qwen-audio-3.1-asr-flash-message。
sample_rateint是

取樣率 (Hz)。

僅支援 16000 Hz。

formatstr是

音訊格式。

有效值:

  • pcm
  • wav
  • mp3
  • opus
  • speex
  • aac
  • amr

重要opus/speex:必須使用 Ogg 封裝;

wav:必須使用 PCM 編碼;

amr:僅支援 AMR-NB 類型。

disfluency_removal_enabledbool否是否過濾語氣詞並潤色輸出結果,預設值為 false。設定為 true 時啟用。以同名關鍵字參數傳入。
intermediate_result_enabledbool否是否回傳串流中間結果。預設值為 false。設定為 true 時,會回傳串流中間結果。透過 parameters 字典傳入。
keep_dialectbool否預設值為 false,將方言轉寫為國語;設為 true 時,會保留方言表達方式。請透過 parameters 字典傳入。完整參數說明請參閱客戶端事件。

僅對最終結果(sentence_end=true)生效;不支援中間結果(sentence_end=false)。

vad_modelstr否可選值:near_meeting_16k (近場) 或 far_field_meeting_16k (遠場,預設值)。請透過 parameters 字典傳入。完整參數說明請參閱客戶端事件。
vocabulary_idstr否

預先編譯的熱詞列表 ID。

需事先呼叫熱詞列表建立 API 產生該 ID;在辨識時傳入此 ID,即可使用列表中的熱詞。

適用於詞彙已知且相對穩定、需要在多次請求間重複使用同一詞表的情境。

使用說明請參見預先編譯熱詞。

vocabularydict否

即時熱詞。

以鍵值對形式傳入,鍵為熱詞文字(string),值為熱詞權重(integer);無需事先建立熱詞列表。權重範圍為 [1, 5] 或 50:[1, 5] 內的值越大,模型越可能輸出該詞;50 表示超級熱詞,可顯著提升召回率,但超級熱詞數量不得超過 50。

適用於臨時的、工作階段層級的熱詞最佳化。

與預先編譯熱詞同時設定時,系統會合併兩類熱詞;若合併後總數超過 2000,將隨機選取 2000 個使用。使用說明請參見即時熱詞。

範例:

import os
import dashscope

client = dashscope.Client(api_key=os.getenv("DASHSCOPE_API_KEY"))

# Instant vocabulary is passed in through parameters
vocab = {"张三": 5, "李四": 5}
recognition = client.audio.asr.recognize(
    model='qwen-audio-3.1-asr-flash-message',
    format='wav',
    sample_rate=16000,
    parameters={"vocabulary": vocab},
)
language_hintslist[str]否待辨識音訊的語言。無預設值;未設定時由模型自動辨識。

最多可設定 4 個值;若超過,僅前 4 個生效。

點擊查看支援的語言代碼

  • zh: 中文
  • en: 英文
  • ja: 日文
  • ko: 韓文
  • vi: 越南文
  • th: 泰文
  • id: 印尼文
  • ms: 馬來文
  • tl: 菲律賓文
  • hi: 印地文
  • ar: 阿拉伯文
  • fr: 法文
  • de: 德文
  • es: 西班牙文
  • pt: 葡萄牙文
  • ru: 俄文
  • it: 義大利文
  • nl: 荷蘭文
  • sv: 瑞典文
  • da: 丹麥文
  • fi: 芬蘭文
  • no: 挪威文
  • el: 希臘文
  • pl: 波蘭文
  • cs: 捷克文
  • hu: 匈牙利文
  • ro: 羅馬尼亞文
  • bg: 保加利亞文
  • hr: 克羅埃西亞文
  • sk: 斯洛伐克文

透過 parameters 字典傳入,例如 parameters={"language_hints": ["zh"]}。

僅對最終結果(sentence_end=true)生效;不支援中間結果(sentence_end=false)。

max_sentence_silenceint否

用於斷句的 VAD 靜音閾值(毫秒)。當一段語音後的靜音時長超過該閾值時,系統判定該句子已結束。

預設值:800。

取值範圍:[200, 6000]。

heartbeatbool否

是否啟用心跳封包。

預設值:False。

  • True:持續傳送靜音音訊時,可保持與伺服器的連線不中斷。
  • False(預設):即使持續傳送靜音音訊,連線也會在逾時後關閉。

靜音音訊指音訊檔案或資料流中不含聲音訊號的內容。靜音音訊可以透過多種方式產生,例如使用 Audacity 或 Adobe Audition 等音訊編輯軟體,或 FFmpeg 等命令列工具。

此欄位於 SDK 1.23.1 引入,並包含於 2.0.1 及之後版本。

speech_noise_thresholdfloat否

用於區分語音與噪音的閾值,用於調整語音活動偵測(VAD)的靈敏度。

取值範圍:[-1.0, 1.0]。

取值說明:

  • 值越接近 -1:噪音偵測閾值降低,噪音被辨識為語音的機率增加,可能導致更多噪音被轉錄
  • 值越接近 +1:噪音偵測閾值提高,語音被誤判為噪音的機率增加,可能導致部分語音被過濾掉

此為進階設定參數,調整後可能顯著影響辨識效果。建議:

  • 調整前充分測試並驗證效果
  • 根據實際音訊環境小幅調整(建議步長為 0.1)

使用 recognize 建立辨識會話時,透過 input 傳入上下文。

參數類型是否必填描述
inputdict否

輸入物件,用於傳入對話上下文。上下文有助於辨識,並可提升特定領域詞彙的辨識準確率。詳細用法請參閱快速入門。

該 dict 必須包含 context 鍵,其值為訊息列表(list[dict])。每個訊息包含以下欄位:

  • role(str,必填):訊息角色。user 表示前幾輪使用者語音的辨識結果或特定領域相關詞彙;assistant 表示前幾輪 LLM 的回覆。
  • content(list[dict],必填):訊息內容列表。每個元素包含 type(str,role 為 user 時設為 input_text,role 為 assistant 時設為 text)與 text(str,文字內容)。

重要上下文訊息(input_text 與 text 類型)各以 5 條為限;超過時保留最近的 5 條。每輪上下文文字總長度不得超過 400 字元;超出部分會從末尾截斷。

重要提供上下文時,context 中訊息的順序很重要:上下文訊息必須按對話輪次排列,且每輪中 user(input_text 類型)必須在對應的 assistant(text 類型)之前。

說明此欄位於 SDK 1.25.23 引入,並包含於 2.0.1 及之後版本。

# Build the input data
input_context = {
    "context": [
        {
            "role": "user",
            "content": [
                {
                    "type": "input_text",
                    "text": "你好啊"
                }
            ]
        },
        {
            "role": "assistant",
            "content": [
                {
                    "type": "text",
                    "text": "你好啊,我是通义千问,有什么可以帮助你的?"
                }
            ]
        }
    ]
}

# 通过 input 参数传入
recognition = client.audio.asr.recognize(
    model='qwen-audio-3.1-asr-flash-message',
    format='wav',
    sample_rate=16000,
    input=input_context,
)

API 參考

Qwen-Audio-ASR-Message

關鍵 API

核心資源 (client.audio.asr)

即時語音辨識能力掛載於 client.audio.asr 資源上:recognize 建立雙向串流辨識工作階段(Recognition),recognize_file 則對本機檔案執行一次性辨識。

成員方法方法簽章描述
recognize
def recognize(self,
              *,
              model: str,
              format: str = "pcm",
              sample_rate: int = 16000,
              vocabulary_id: str = None,
              disfluency_removal_enabled: bool = None,
              diarization_enabled: bool = None,
              parameters: Dict = None,
              input: Dict = None,
              phrase_id: str = None,
              ...) -> Recognition

建立雙向串流辨識工作階段;進入 with 上下文時會自動呼叫 start 以建立連線並傳送任務。

傳送音訊與消費事件必須並行執行(與 send_audio_frame、events()/results() 及 stop 搭配使用)。

recognize_file
def recognize_file(self,
                   path: str,
                   *,
                   model: str,
                   format: str = "pcm",
                   sample_rate: int = 16000,
                   ...) -> Iterator[Dict]

基於本機檔案的非串流呼叫:自動分塊傳送音訊並驅動任務直至完成,逐一產生伺服器端事件。此方法需要待辨識檔案的讀取權限。

start
def start(self)

啟動語音辨識:建立連線、傳送任務並等待 task-started。進入 with 上下文時會自動呼叫;啟動成功後才能傳送音訊。

send_audio_frame
def send_audio_frame(self, buffer: bytes)

推送音訊。每次推送的音訊區塊不宜過大或過小;建議每個區塊的音訊時長約 100ms,大小介於 1KB 至 16KB 之間。

辨識結果透過事件迭代 (events()/results())取得。

stop
def stop(self)
停止語音辨識:僅通知伺服器輸入已結束;接收執行緒必須繼續消費 events(),直到 task-finished 事件為止。
events / results
def events(self) -> Iterator[Dict]
def results(self) -> Iterator[RecognitionResult]

迭代伺服器端事件:events() 產生原始事件 dict(辨識文字位於 payload.output.sentence);results() 僅產生辨識結果幀,回傳型別化的辨識結果 (RecognitionResult)物件(心跳幀會被過濾掉)。

close
def close(self)

關閉辨識工作階段。離開 with 上下文時自動呼叫。

request_id / first_package_delay / last_package_delay / last_response
rec.request_id
rec.first_package_delay
rec.last_package_delay
rec.last_response

取得 request_id、首包延遲(從傳送第一個音訊封包到收到第一個辨識結果之間的延遲)與末包延遲(從傳送 stop 指令到送達最後一個辨識結果的時間);於任務完成後使用。last_response 是最近一次成功讀取的原始訊息,可用於取得任務失敗的錯誤資訊。工作階段關閉後仍可讀取。

更新對話上下文

在辨識任務執行期間呼叫 update_context 更新對話上下文,以輔助後續音訊的辨識。此方法需要 DashScope Python SDK 2.0.1 或更新版本。

def update_context(self, context: dict)
  • 何時呼叫:進入 with 上下文(會自動呼叫 start)開始串流辨識之後、呼叫 stop 之前。
  • 參數:context 是一個字典;傳入 continue-task 事件的 payload.input 物件,其中包含 context 欄位。不要再用 payload 或 input 額外包裹。
  • 範圍與參數限制:參見 continue-task。

以下範例重複使用已啟動的 recognition 實例。

payload_input = {
    "context": [
        {
            "role": "user",
            "content": [{"type": "input_text", "text": "你好啊"}]
        },
        {
            "role": "assistant",
            "content": [{"type": "text", "text": "你好啊,我是通义千问,有什么可以帮助你的?"}]
        }
    ]
}
recognition.update_context(context=payload_input)
事件迭代 (events()/results())

在雙向串流呼叫期間,伺服器以事件形式向用戶端回傳關鍵過程資訊與資料。您需要在接收執行緒中迭代工作階段的 events()(原始事件 dict)或 results()(型別化的辨識結果幀),以處理伺服器回傳的資訊或資料。

# 迭代原始事件:识别文本位于 payload.output.sentence
def receive_events(rec):
    for event in rec.events():
        payload = event.get('payload') or {}
        sentence = (payload.get('output') or {}).get('sentence') or {}
        if sentence.get('text') and not sentence.get('heartbeat'):
            print('识别文本:', sentence['text'])


# 或只迭代识别结果帧(返回 RecognitionResult,心跳帧已过滤)
def receive_results(rec):
    for result in rec.results():
        sentence = result.get_sentence()
        if sentence and 'text' in sentence:
            print('识别文本:', sentence['text'])
事件/迭代方法輸出傳回值描述
event["header"]["event"] == "task-started"

task-started 事件

None

由 start() 內部讀取,並在啟動返回時儲存到 last_response;events() 不會再次產生該事件。

def events(self) -> Iterator[Dict]

event:伺服器端事件 dict

迭代器

當伺服器有回應時產生事件。辨識結果位於 payload.output.sentence,其中可能包含心跳事件或空文字事件,應用程式可視需要忽略。請在單一接收執行緒中持續消費,不要建立多個並發讀取器。

def results(self) -> Iterator[RecognitionResult]

result:辨識結果(RecognitionResult)

迭代器

僅產生辨識結果幀(心跳幀已過濾);所有辨識結果返回完畢後迭代結束。

try:
    ...
except DashScopeError as e:
    print(e.code, e.message, e.request_id)

DashScopeError 例外

None

發生例外時在傳送/接收執行緒中拋出;可用 try/except 捕捉。

event["header"]["event"] == "task-finished"

task-finished 事件

None

在伺服器完成全部辨識後由 events() 產生,之後迭代結束;發送 stop() 後仍必須讀取該事件。

回應結果

辨識結果(RecognitionResult)

RecognitionResult 表示迭代 session 的 results() 時產生的辨識結果幀(雙向串流呼叫與非串流呼叫均可使用;events() 產生的是原始事件 dict,若需要此型別化檢視請改用 results())。

成員方法方法簽章描述
get_sentence
def get_sentence(self) -> Union[Dict[str, Any], List[Any]]

取得目前已辨識的句子及其時間戳記資訊。此方法回傳 Dict[str, Any](句子資訊)。

詳情請參閱句子資訊(Sentence)。

request_id
result.request_id
與目前事件對應之請求的 request_id。
is_sentence_end
def is_sentence_end(self) -> bool
判斷目前句子是否已結束。此方法檢查 get_sentence() 回傳的單句資訊中 end_time 欄位是否為 None——當 end_time 不為 None 時,句子已結束。
句子資訊(Sentence)

Sentence 類別的成員如下:

參數類型說明
begin_timeint句子開始時間,單位為 ms。
end_timeint句子結束時間,單位為毫秒。
textstr辨識出的文字。
words字詞時間戳記資訊 (Word)清單集合字詞時間戳記資訊。
字詞時間戳記資訊 (Word)

Word 類別的成員如下:

參數類型說明
begin_timeint字詞開始時間,單位為毫秒。
end_timeint字詞結束時間,單位為毫秒。
textstr字詞。
punctuationstr標點符號。

错误码

如遇报错问题,请参见错误码进行排查。

若问题仍未解决,可加入语音 SDK 示例仓库中列出的开发者群反馈问题,并提供Request ID,以便进一步排查问题。