Skip to main content

Qwen-Audio-ASR-Message Node.js SDK

Use the speech Node.js SDK to call Qwen-Audio-ASR-Message, handle recognition results, and update context during a task.

Install the SDK

Requires Node.js 18 or later. Download the SDK 0.1.0 package, then run this command in your project:
npm install ./dashscope-sdk-nodejs-0.1.0.tgz

Quick start

Obtain an API key in the console and set it as the DASHSCOPE_API_KEY environment variable. Download the sample audio as input.mp3 and convert it to 16 kHz, 16-bit, mono PCM:
ffmpeg -i input.mp3 -f s16le -ac 1 -ar 16000 input.pcm
Save the following example as example.mjs and run node example.mjs.
import { readFile } from 'node:fs/promises'
import { setTimeout as sleep } from 'node:timers/promises'
import { RecognitionClient } from 'dashscope-sdk-nodejs/asr'

const pcm = await readFile('input.pcm')
const asr = new RecognitionClient({
  apiKey: process.env.DASHSCOPE_API_KEY,
  workspaceId: process.env.DASHSCOPE_WORKSPACE_ID,
  baseUrl: 'dashscope.aliyuncs.com',
  model: 'qwen-audio-3.1-asr-flash-message',
  format: 'pcm',
  sampleRate: 16000,
})
asr.on('sentenceEnd', sentence => console.log('Final sentence:', sentence.text))
asr.on('error', err => console.error(err.code, err.message))

try {
  await asr.start()
  for (let offset = 0; offset < pcm.length; offset += 3200) {
    asr.sendAudio(pcm.subarray(offset, offset + 3200))
    await sleep(100)
  }
  await asr.finish()
} finally {
  asr.close()
}

API reference

Constructor options

Constructor options for RecognitionClient:
ParameterTypeRequiredDescription
apiKeystringNoAPI key. Defaults to DASHSCOPE_API_KEY.
workspaceIdstringNoWorkspace ID. Defaults to DASHSCOPE_WORKSPACE_ID.
baseUrlstringNoService hostname. Default: dashscope.aliyuncs.com (Beijing).
modelstringYesSet the model ID to qwen-audio-3.1-asr-flash-message.
format'pcm' | 'wav' | 'mp3' | 'opus' | 'speex' | 'aac' | 'amr'NoAudio format. Default: pcm. WAV uses PCM encoding, Opus/Speex use Ogg containers, and AMR uses AMR-NB.
sampleRatenumberNoAudio sample rate. Use 16000 Hz.
vocabularyIdstringNoPrecompiled vocabulary ID.
languageHintsstring[]NoRecognition language hints. Up to the first 4 values take effect. Language is detected automatically if omitted.
disfluencyRemovalEnabledbooleanNoRemove disfluencies and polish results. Default: false.
maxSentenceSilencenumberNoVAD sentence-ending silence threshold in ms: [200,6000]; default: 800.
heartbeatbooleanNoSilence keepalive. Default: false; keep sending silent audio when enabled.
contextAsrContextMessage[]NoRecognition context. Message format: { role, content: [{ type: "input_text", text }] }, with role set to user or assistant. Up to 5 messages per role and fewer than 400 characters in total, ordered by conversation turn.
parametersPartial<RecognitionParameters>NoAdditional recognition parameters, such as vad_model, keep_dialect, and vocabulary.
connectTimeoutMsnumberNoConnection timeout in ms. Default: 10000.
taskTimeoutMsnumberNoStart/finish acknowledgement timeout in ms. Default: 60000; 0 disables the timeout.
parameters.vad_model'near_meeting_16k' | 'far_field_meeting_16k'NoNear-field or far-field VAD. Default: far_field_meeting_16k.
parameters.keep_dialectbooleanNoPreserve dialect expressions. Default: false.
parameters.vocabularyRecord<string, number>NoInstant vocabulary: words as keys and weights in [1,5] or 50 as values.
parameters.speech_noise_thresholdnumberNoVAD sensitivity threshold: [-1,1].
parameters.intermediate_result_enabledbooleanNoReturn intermediate recognition results. Default: false.

Main methods

MethodReturn valueDescription
start()Promise<void>Start recognition; send audio after it resolves.
sendAudio(audio: Buffer | Uint8Array)voidSend audio frames in the configured format and sample rate.
updateContext(context: AsrContextMessage[])voidUpdate recognition context after starting and before finishing input.
finish()Promise<void>Finish audio input and wait for completion. Text arrives through callbacks.
close(code?: number, reason?: string)voidClose the connection and release task resources.

Callback events

Register callbacks with on(event, listener). See server events for the full event fields.
EventPayloadDescription
started{ taskId: string }Task has started and accepts input.
result{ text: string; sentence_end: boolean; sentence_begin?: boolean; words?: RecognitionWord[] }Intermediate or final sentence, excluding heartbeat results.
sentenceEnd{ text: string; sentence_end: boolean; sentence_begin?: boolean; words?: RecognitionWord[] }Final sentence with sentence_end === true.
finished{ taskId: string; duration?: number; usage?: RecognitionUsage }Task has finished and local task state is cleared.
failed / errorDashScopeErrorCall error with code, message, and request identifiers.
close{ code: number; reason: string }Underlying connection-close notification.
eventServerEventRaw service JSON message.