豆包实时语音识别

v1.0.1发布于:2025-02-07 10:11

说明文档
回复列表 (0)

语音识别插件

这是一个语音识别插件,基于字节跳动火山引擎的语音识别服务,支持一次性识别和流式识别两种模式。

介绍

本插件提供了两种语音识别方式:

  1. 一次性识别 - 适合短音频文件的快速识别
  2. 流式识别 - 适合需要实时识别的场景,可以一边输入音频一边识别

标识

调用插件的时候需要用到标识,标识是唯一的,不能重复,建议使用英文。对应插件 plugin.json 中的 key 字段

  • 标识:hs-asr

配置

{
  "appid": "your_app_id",
  "token": "your_token"
}
  • appid:火山引擎应用ID,详情
  • token:访问令牌,详情

方法

下面是插件提供的一些方法:

once

一次性识别,适用于短音频文件

/**
 * 一次性识别
 * @param audioUrl 音频文件URL
 * @param audioOptions 音频参数配置(可选)
 */
async once(
  audioUrl: string,
  audioOptions?: {
    format?: "raw" | "wav" | "mp3" | "ogg";  // 音频格式
    codec?: "raw" | "opus";                   // 编码格式
    rate?: number;                            // 采样率
    bits?: number;                            // 位深
    channel?: number;                         // 声道数
  }
)

stream

流式识别,支持实时音频输入并获取识别结果

/**
 * 流式识别
 * @param options 音频参数配置
 * @param callbacks 回调函数
 */
async stream(
  options: {
    format?: "pcm" | "wav" | "ogg";          // 音频格式
    rate?: number;                            // 采样率
    bits?: number;                            // 位深
    channel?: number;                         // 声道数
    codec?: "raw" | "opus";                   // 编码格式
  },
  callbacks: {
    onError?: (error: any) => void;          // 错误回调
    onFinal?: (text: string) => void;        // 最终识别结果回调
    onInterim?: (text: string) => void;      // 中间识别结果回调
  }
)

调用示例

@Inject()
pluginService: PluginService;

// 获取插件实例
const instance = await this.pluginService.getInstance('asr');

// 一次性识别
const text = await instance.once(
  'https://example.com/audio.mp3',
  { 
    format: 'mp3'
  }
);
console.log('识别结果:', text);

// 流式识别
const client = await instance.stream(
  {
    format: 'wav',
    rate: 16000,
    bits: 16,
    channel: 1
  },
  {
    onInterim: (text) => {
      console.log('中间识别结果:', text);
    },
    onFinal: (text) => {
      console.log('最终识别结果:', text);
    },
    onError: (error) => {
      console.error('识别错误:', error);
    }
  }
);

// 读取音频文件
const fs = require('fs');
const audioFile = fs.readFileSync('audio.wav');

// 每次发送64KB数据
const chunkSize = 64 * 1024;

// 分片发送音频
for (let offset = 0; offset < audioFile.length; offset += chunkSize) {
  const chunk = audioFile.slice(offset, offset + chunkSize);
  await client.send(chunk);
}

// 结束识别
client.done();

更新日志

  • v1.0.0 (2024-02-06)
    • 初始版本
    • 支持一次性识别
    • 支持流式识别
    • 支持多种音频格式和参数配置