🎤 基于讯飞语音识别 API 的实时语音转文字 JavaScript SDK
特性
- 🎯 实时语音识别 - 支持实时音频流识别
- 🔄 智能音量监听 - 自动检测音量变化并启动识别
- 🌐 WebSocket 连接 - 基于 WebSocket 的实时通信
- 🎛️ 灵活配置 - 支持多种语言、领域和音频格式
- 📦 TypeScript 支持 - 完整的类型定义
- 🔧 模块化设计 - 采用处理器链模式,易于扩展
安装
bash
npm install xunfei-lat
# 或
pnpm install xunfei-lat
# 或
yarn add xunfei-lat
快速开始
1. 配置系统参数
首先需要在讯飞开放平台申请相关密钥:
javascript
import xunfeiLat from 'xunfei-lat'
// 配置系统参数
xunfeiLat.config({
API_SECRET: 'your_api_secret',
APPID: 'your_appid',
API_KEY: 'your_api_key'
})
2. 创建实例
javascript
// 创建语音识别实例
const latInstance = xunfeiLat.create()
3. 监听事件
javascript
// 监听识别结果
latInstance.on('appResultText', (text) => {
console.log('最终识别结果:', text)
})
// 监听实时识别过程
latInstance.on('appResponseText', (text) => {
console.log('实时识别结果:', text)
})
// 监听识别完成
latInstance.on('appFinish', () => {
console.log('识别完成')
})
4. 开始识别
javascript
// 手动开始录音识别
latInstance.start()
API 参考
配置参数
SystemConfig(系统配置)
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
API_SECRET |
string |
✅ | 讯飞平台申请的密钥 |
APPID |
string |
✅ | 讯飞平台申请的应用ID |
API_KEY |
string |
✅ | 讯飞平台申请的API密钥 |
BusinessParams(业务参数)
参数 | 类型 | 默认值 | 说明 |
---|---|---|---|
language |
`'zh_cn' | 'en_us'` | 'zh_cn' |
domain |
string |
'iat' |
应用领域 |
accent |
'mandarin' |
'mandarin' |
方言类型 |
vad_eos |
number |
3600000 |
静默检测时间(ms) |
dwa |
'wpgs' |
'wpgs' |
动态修正 |
ptt |
`0 | 1` | 1 |
rlang |
`'zh-cn' | 'zh-hk'` | 'zh-cn' |
nunum |
`0 | 1` | 1 |
SectionDelayParams(延迟控制参数)
参数 | 类型 | 默认值 | 说明 |
---|---|---|---|
autoControl |
boolean |
true |
是否自动控制延迟 |
initialDelay |
number |
3500 |
初始延迟时间(ms) |
subsequentDelay |
number |
3000 |
后续延迟时间(ms) |
实例方法
start(): void
手动开始录音和语音识别。
watch(): void
启动智能音量监听模式。当检测到音量大于20%且系统处于离线状态时自动开始识别。
finish(): void
结束当前的录音和识别过程。
on(eventName: string, callback: Function): void
监听事件。
事件
事件名 | 参数 | 说明 |
---|---|---|
appResultText |
text: string |
最终识别结果 |
appResponseText |
text: string |
实时识别过程中的文本 |
appFinish |
- | 识别完成 |
完整示例
javascript
import xunfeiLat from 'xunfei-lat'
// 1. 配置系统参数
xunfeiLat.config({
API_SECRET: 'your_api_secret',
APPID: 'your_appid',
API_KEY: 'your_api_key'
})
// 2. 创建实例
const latInstance = xunfeiLat.create({}, {
autoControl: false
})
// 3. 监听事件
latInstance.on('appResultText', (text) => {
console.log('识别完成:', text)
})
latInstance.on('appResponseText', (text) => {
console.log('实时结果:', text)
})
latInstance.on('appFinish', () => {
console.log('识别结束')
})
// 4. 开始识别
const startBtn = document.createElement('button')
startBtn.id = 'startBtn'
startBtn.textContent = '开始识别'
document.body.appendChild(startBtn)
const stopBtn = document.createElement('button')
stopBtn.id = 'stopBtn'
stopBtn.textContent = '结束识别'
document.body.appendChild(stopBtn)
startBtn.addEventListener('click', () => {
latInstance.start()
})
stopBtn.addEventListener('click', () => {
latInstance.end()
})
常见问题
Q: 为什么无法录音?
A: 请确保:
- 使用 HTTPS 协议访问
- 浏览器已授权麦克风权限
- 设备有可用的音频输入设备
许可证
ISC