### Install dependencies with npm install Source: https://github.com/agions/xfyun-sdk/blob/main/CONTRIBUTING.md Run this command in the project root to install all required dependencies. Requires Node.js >= 18 and npm >= 9. ```bash npm install ``` -------------------------------- ### startRecognition function using start() Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/asr.md Example of starting recognition after obtaining microphone access. Logs an error if permission fails. ```typescript async function startRecognition() { try { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); recognizer.start(); } catch (err) { console.error('获取麦克风权限失败:', err); } } ``` -------------------------------- ### start() Source: https://github.com/agions/xfyun-sdk/blob/main/docs/DOCUMENT_DESIGN.md Starts the speech recognition process. Requires microphone permission to be granted first, and it is recommended to call this method after user interaction. ```APIDOC ## start() ### Description Starts the speech recognition process. Requires microphone permission to be granted first, and it is recommended to call this method after user interaction. ### Method start ### Signature ```typescript recognizer.start(): Promise ``` ### Notes - Requires microphone permission to be granted first. - Recommended to call after user interaction. ``` -------------------------------- ### Install xfyun-sdk via npm, pnpm, or yarn Source: https://github.com/agions/xfyun-sdk/blob/main/README.md Install the xfyun-sdk package using your preferred package manager. Choose one command based on your environment. ```bash # npm npm install xfyun-sdk ``` ```bash # pnpm pnpm add xfyun-sdk ``` ```bash # yarn yarn add xfyun-sdk ``` -------------------------------- ### start() 方法:开始语音识别 Source: https://github.com/agions/xfyun-sdk/blob/main/docs/DOCUMENT_DESIGN.md 调用前需获取麦克风权限,建议在用户交互后调用。返回 Promise。 ```typescript recognizer.start(): Promise ``` -------------------------------- ### on('start') Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/tts.md Event listener for when synthesis starts. ```APIDOC ## on('start') ### Description Event listener for when synthesis starts. ### Method on ### Event Name start ### Example ```typescript synthesizer.on('start', () => { console.log('合成开始'); }); ``` ``` -------------------------------- ### TTS Speech Synthesis Quick Start Source: https://github.com/agions/xfyun-sdk/blob/main/README.md Initializes an XfyunTTS synthesizer with configuration and event callbacks, then starts synthesis with text, stops, and destroys it. Uses environment variables for credentials and supports streaming audio data and progress callbacks. ```javascript import { XfyunTTS } from 'xfyun-sdk'; const synthesizer = new XfyunTTS( { appId: import.meta.env.VITE_XFYUN_APP_ID, apiKey: import.meta.env.VITE_XFYUN_API_KEY, apiSecret: import.meta.env.VITE_XFYUN_API_SECRET, voice_name: 'xiaoyan', // 青年女声 speed: 50, // 语速 0-100 pitch: 50, // 音调 0-100 volume: 50, // 音量 0-100 audioFormat: 'mp3', // mp3/wav/pcm }, { onStart: () => console.log('🟢 合成开始'), onEnd: () => console.log('🔴 合成结束'), onAudioData: (audioData) => { // 流式音频数据 console.log('收到音频:', audioData.byteLength, 'bytes'); }, onProgress: (current, total) => { console.log(`进度: ${current}/${total}`); }, onError: (error) => console.error('❌ 错误:', error), } ); // 开始合成 synthesizer.start('你好,这是语音合成测试。'); // 停止合成 synthesizer.stop(); // 销毁实例 synthesizer.destroy(); ``` -------------------------------- ### Install dependencies Source: https://github.com/agions/xfyun-sdk/blob/main/examples/vue-demo/README.md Navigate to the vue-demo directory and install npm dependencies. ```bash cd examples/vue-demo npm install ``` -------------------------------- ### start() Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/asr.md Starts speech recognition. Requires microphone permission, recommended to call after user interaction. ```APIDOC ## start() ### Description Starts speech recognition. Requires microphone permission, recommended to call after user interaction. ### Method start ### Signature `recognizer.start(): Promise` ### Request Example ```typescript async function startRecognition() { try { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); recognizer.start(); } catch (err) { console.error('获取麦克风权限失败:', err); } } ``` ``` -------------------------------- ### Example git commit commands with Conventional Commits Source: https://github.com/agions/xfyun-sdk/blob/main/CONTRIBUTING.md These example commands show how to format commit messages for different types: feat for new features, fix for bug fixes, and docs for documentation updates. Use them as templates for your own commits. ```bash git commit -m "feat(recognizer): 添加 autoStart 功能" ``` ```bash git commit -m "fix(translator): 修复 translateText 参数校验" ``` ```bash git commit -m "docs(api): 更新 ASR API 文档" ``` -------------------------------- ### XfyunASR.start() Source: https://github.com/agions/xfyun-sdk/blob/main/README.md Starts the speech recognition process. This method initiates the WebSocket connection and begins recording audio for recognition. ```APIDOC ## XfyunASR.start() ### Description Starts the speech recognition process. This method initiates the WebSocket connection and begins recording audio for recognition. ### Method start() ### Return Value `Promise` ### Parameters None ### Response #### Success Response - **Promise** - Resolves when the recognition starts successfully. ``` -------------------------------- ### Start development server Source: https://github.com/agions/xfyun-sdk/blob/main/examples/vue-demo/README.md Run the Vite development server. Open http://localhost:5173 to use the demo. ```bash npm run dev ``` -------------------------------- ### ASR Speech Recognition Quick Start Source: https://github.com/agions/xfyun-sdk/blob/main/README.md Initializes an XfyunASR recognizer with configuration and event callbacks, then starts, stops, and destroys it. Uses environment variables for credentials and supports Chinese Mandarin with a 3000ms VAD end-of-speech timeout. ```javascript import { XfyunASR } from 'xfyun-sdk'; const recognizer = new XfyunASR( { appId: import.meta.env.VITE_XFYUN_APP_ID, apiKey: import.meta.env.VITE_XFYUN_API_KEY, apiSecret: import.meta.env.VITE_XFYUN_API_SECRET, language: 'zh_cn', accent: 'mandarin', vadEos: 3000, }, { onStart: () => console.log('🟢 识别已开始'), onStop: () => console.log('🔴 识别已停止'), onRecognitionResult: (text, isEnd) => { console.log(`📝 ${isEnd ? '[最终]' : '[中间]'} ${text}`); }, onProcess: (volume) => { const bar = '█'.repeat(Math.round(volume * 10)); console.log(`🔊 ${bar}`); }, onError: (error) => console.error('❌ 错误:', error), } ); recognizer.start(); recognizer.stop(); recognizer.destroy(); ``` -------------------------------- ### Basic recognition example Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/asr.md Creates a recognizer with default settings, listens for 'result' events, and starts recognition. Replace YOUR_APP_ID, YOUR_API_KEY, and YOUR_API_SECRET with actual credentials. ```typescript const recognizer = createRecognizer({ appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY', apiSecret: 'YOUR_API_SECRET', }); recognizer.on('result', (text) => { console.log(text); }); recognizer.start(); ``` -------------------------------- ### Development commands for docs, tests, lint, and build Source: https://github.com/agions/xfyun-sdk/blob/main/CONTRIBUTING.md These commands are used during development: start the docs dev server, run tests, run tests with coverage, run ESLint, and build the project. Each command is executed separately. ```bash # 启动开发服务器 npm run docs:dev ``` ```bash # 运行测试 npm run test ``` ```bash # 运行测试并查看覆盖率 npm run test:coverage ``` ```bash # 运行 ESLint npm run lint ``` ```bash # 构建项目 npm run build ``` -------------------------------- ### start event handler Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/tts.md Event handler for the 'start' event, triggered when synthesis starts. ```typescript synthesizer.on('start', () => { console.log('合成开始'); }); ``` -------------------------------- ### Event: start Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/asr.md Triggered when recognition starts. ```APIDOC ## Event: start ### Description Triggered when recognition starts. ### Event Name start ### Request Example ```typescript recognizer.on('start', () => { console.log('识别开始'); }); ``` ``` -------------------------------- ### start event handler Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/asr.md Triggered when recognition starts. ```typescript recognizer.on('start', () => { console.log('识别开始'); }); ``` -------------------------------- ### start() Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/translator.md Starts the translation process. In text translation mode, the text parameter is required; in speech translation mode, it can be omitted. ```APIDOC ## start() ### Description Starts the translation process. In text translation mode, the text parameter is required; in speech translation mode, it can be omitted. ### Method start ### Signature ```typescript translator.start(text?: string): Promise ``` ### Parameters - **text** (string) - Optional - The text to translate (required in text translation mode, optional in speech translation mode) ``` -------------------------------- ### translator.on('start') Source: https://github.com/agions/xfyun-sdk/blob/main/docs-dist/api/translator.html Event listener for translation start. Triggered when translation begins. ```APIDOC ## translator.on('start') ### Description Event listener for translation start. Triggered when translation begins. ### Event `start` ### Example ```typescript translator.on('start', () => { console.log('翻译开始'); }); ``` ``` -------------------------------- ### Recognizer.start() Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/asr.md Starts the speech recognition process. The recognizer must be created with valid credentials before calling this method. ```APIDOC ## Recognizer.start() ### Description Starts the speech recognition process. The recognizer must be created with valid credentials before calling this method. ### Method Function ### Signature `start(): void` ### Parameters None ### Returns - **void** - No return value. ### Example ```typescript recognizer.start(); ``` ``` -------------------------------- ### XfyunTranslator (Instance) - Text Translation Source: https://github.com/agions/xfyun-sdk/blob/main/README.md Instance-based text translation. Create a translator instance with configuration and callbacks, then start the translation process. ```APIDOC ## XfyunTranslator (Instance) - Text Translation ### Description Instance-based text translation. Create a translator instance with configuration and callbacks, then start the translation process. ### Method Instance Method ### Constructor `new XfyunTranslator(config, callbacks)` ### Parameters #### config - **appId** (string) - Required - The Xfyun application ID. - **apiKey** (string) - Required - The Xfyun API key. - **apiSecret** (string) - Required - The Xfyun API secret. - **type** (string) - Required - Set to 'text' for text translation. - **from** (string) - Required - Source language code (e.g., 'en' for English). - **to** (string) - Required - Target language code (e.g., 'ja' for Japanese). #### callbacks - **onResult** (function) - Optional - Callback invoked with the translation result object. ### Methods #### start(text) - **text** (string) - Required - The text to translate. ### Response #### onResult callback - **targetText** (string) - The translated text. ### Request Example ```javascript const translator = new XfyunTranslator( { appId: 'your_app_id', apiKey: 'your_api_key', apiSecret: 'your_api_secret', type: 'text', from: 'en', to: 'ja', }, { onResult: (result) => { console.log('翻译结果:', result.targetText); }, } ); translator.start('Hello, how are you?'); ``` ``` -------------------------------- ### speak() usage examples Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/tts.md Basic usage and usage with configuration options for the speak() method. ```typescript // 基础使用 synthesizer.speak('你好,世界'); ``` ```typescript // 带配置 await synthesizer.speak('你好', { voice_name: 'xiaoyan', speed: 60, }); ``` -------------------------------- ### TTS voice selection examples (XfyunTTS) Source: https://github.com/agions/xfyun-sdk/blob/main/README.md Shows four different `voice_name` values for TTS: 'xiaoyan' (young female), 'aisxiaofeng' (young male), 'aisjiuyuan' (Sichuan dialect), and 'aisxiaowawa' (child voice). Each creates a separate `XfyunTTS` instance. ```javascript // 青年女声 const tts1 = new XfyunTTS({ voice_name: 'xiaoyan' }, handlers); // 青年男声 const tts2 = new XfyunTTS({ voice_name: 'aisxiaofeng' }, handlers); // 四川话 const tts3 = new XfyunTTS({ voice_name: 'aisjiuyuan' }, handlers); // 童声 const tts4 = new XfyunTTS({ voice_name: 'aisxiaowawa' }, handlers); ``` -------------------------------- ### 环境变量模板文件 (.env.example) Source: https://github.com/agions/xfyun-sdk/blob/main/docs/guide/authentication.md 作为模板提交到 Git,供其他开发者参考。 ```env # .env.example VITE_XFYUN_APP_ID=your_app_id VITE_XFYUN_API_KEY=your_api_key VITE_XFYUN_API_SECRET=your_api_secret ``` -------------------------------- ### 更新 .gitignore 以保留 .env.example Source: https://github.com/agions/xfyun-sdk/blob/main/docs/guide/authentication.md 在 .gitignore 中添加规则,忽略环境变量文件但保留 .env.example。 ```gitignore # 环境变量 .env .env.local .env.*.local !.env.example ``` -------------------------------- ### Event: start Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/translator.md Triggered when translation starts. ```APIDOC ## Event: start ### Description Triggered when translation starts. ### Usage ```typescript translator.on('start', () => { console.log('翻译开始'); }); ``` ``` -------------------------------- ### createAudioContext() Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/utils.md 创建 AudioContext。返回一个 AudioContext 实例,等价于 `new (window.AudioContext || window.webkitAudioContext)()`。 ```APIDOC ## createAudioContext() ### Description 创建 AudioContext。 ### Request Example ```typescript import { createAudioContext } from 'xfyun-sdk'; const context = createAudioContext(); // 等价于: // const context = new (window.AudioContext || window.webkitAudioContext)(); ``` ``` -------------------------------- ### Listen for translation start event Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/translator.md Registers a listener for the 'start' event, which fires when translation begins. ```typescript translator.on('start', () => { console.log('翻译开始'); }); ``` -------------------------------- ### HTML 示例运行命令 Source: https://github.com/agions/xfyun-sdk/blob/main/examples/README.md 进入 examples/html 目录并直接在浏览器中打开 index.html。 ```bash cd examples/html # 直接在浏览器中打开 index.html ``` -------------------------------- ### Start translation with optional text Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/translator.md Starts the translation process. The text parameter is required for text translation mode but can be omitted for speech translation mode. ```typescript translator.start(text?: string): Promise ``` -------------------------------- ### Include xfyun-sdk via CDN and access classes Source: https://github.com/agions/xfyun-sdk/blob/main/README.md Load the UMD build from jsDelivr and access the SDK classes from the global `window.xfyunSdk` object. This is for browser usage without a bundler. ```html ``` ```html ``` -------------------------------- ### createAudioContext() 创建 AudioContext Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/utils.md 创建 AudioContext,等价于 new (window.AudioContext || window.webkitAudioContext)()。 ```typescript import { createAudioContext } from 'xfyun-sdk'; const context = createAudioContext(); // 等价于: // const context = new (window.AudioContext || window.webkitAudioContext)(); ``` -------------------------------- ### Copy .env.example to .env Source: https://github.com/agions/xfyun-sdk/blob/main/examples/vue-demo/README.md Copy the environment template to create your local .env file. ```bash cp .env.example .env ``` -------------------------------- ### Translate text using static method and voice using instance method Source: https://github.com/agions/xfyun-sdk/blob/main/docs/guide/getting-started.md Shows two translation approaches: static XfyunTranslator.translateText for text translation, and createTranslator with type 'asr' for voice translation. The instance method listens for 'result' events and starts with start(). ```typescript import { createTranslator } from 'xfyun-sdk'; // 文本翻译(静态方法) const result = await XfyunTranslator.translateText({ text: '你好', from: 'cn', to: 'en', appId: import.meta.env.VITE_XFYUN_APP_ID, apiKey: import.meta.env.VITE_XFYUN_API_KEY, apiSecret: import.meta.env.VITE_XFYUN_API_SECRET, }); console.log(result); // 'hello' // 语音翻译(实例方法) const translator = createTranslator({ appId: import.meta.env.VITE_XFYUN_APP_ID, apiKey: import.meta.env.VITE_XFYUN_API_KEY, apiSecret: import.meta.env.VITE_XFYUN_API_SECRET, type: 'asr', // 语音翻译模式 from: 'cn', to: 'en', }); translator.on('result', (text) => { console.log('翻译结果:', text); }); translator.start(); ``` -------------------------------- ### React 示例运行命令 Source: https://github.com/agions/xfyun-sdk/blob/main/examples/README.md 进入 examples/react-demo 目录,安装依赖并启动开发服务器。 ```bash cd examples/react-demo npm install npm run dev ``` -------------------------------- ### 快速使用 createRecognizer Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/asr.md 初始化识别器并开始语音识别。需要提供 appId、apiKey 和 apiSecret。监听 'result' 事件获取识别文本,调用 start() 开始识别。 ```typescript import { createRecognizer } from 'xfyun-sdk'; const recognizer = createRecognizer({ appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY', apiSecret: 'YOUR_API_SECRET', }); recognizer.on('result', (text) => { console.log(text); }); recognizer.start(); ``` -------------------------------- ### 安装 xfyun-sdk Source: https://github.com/agions/xfyun-sdk/blob/main/docs/index.md 使用 npm 安装 xfyun-sdk 包。 ```bash npm install xfyun-sdk ``` -------------------------------- ### 文本翻译:静态方法与实例方法 Source: https://github.com/agions/xfyun-sdk/blob/main/README.md 使用 XfyunTranslator 进行文本翻译。推荐使用静态方法 translateText,传入配置对象(appId、apiKey、apiSecret、from、to)并返回包含 sourceText 和 targetText 的结果。也可创建实例并调用 start 方法,通过 onResult 回调获取翻译结果。 ```javascript import { XfyunTranslator } from 'xfyun-sdk'; // 方式一:静态方法(推荐) const result = await XfyunTranslator.translateText( '你好,世界!', { appId: import.meta.env.VITE_XFYUN_APP_ID, apiKey: import.meta.env.VITE_XFYUN_API_KEY, apiSecret: import.meta.env.VITE_XFYUN_API_SECRET, from: 'cn', to: 'en', } ); console.log(result.sourceText); // 你好,世界! console.log(result.targetText); // Hello, World! // 方式二:实例方法 const translator = new XfyunTranslator( { appId: 'your_app_id', apiKey: 'your_api_key', apiSecret: 'your_api_secret', type: 'text', from: 'en', to: 'ja', }, { onResult: (result) => { console.log('翻译结果:', result.targetText); }, } ); translator.start('Hello, how are you?'); ``` -------------------------------- ### getSupportedAudioFormats() Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/utils.md 获取支持的音频格式列表。返回一个包含支持的音频格式字符串的数组。 ```APIDOC ## getSupportedAudioFormats() ### Description 获取支持的音频格式列表。 ### Request Example ```typescript import { getSupportedAudioFormats } from 'xfyun-sdk'; const formats = getSupportedAudioFormats(); console.log(formats); // ['audio/L16;rate=16000', 'audio/L16;rate=8000', ...] ``` ``` -------------------------------- ### Vue 示例运行命令 Source: https://github.com/agions/xfyun-sdk/blob/main/examples/README.md 进入 examples/vue-demo 目录,安装依赖并启动开发服务器。 ```bash cd examples/vue-demo npm install npm run dev ``` -------------------------------- ### Translator.start Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/translator.md Instance method to start the translation process. Begins listening and translating based on the configured options. ```APIDOC ## Translator.start ### Description Instance method to start the translation process. Begins listening and translating based on the configured options. ### Method Instance method ### Parameters No parameters ### Response #### Success Response - No return value specified ### Request Example ```typescript translator.start(); ``` ``` -------------------------------- ### 增强代码块:使用 DemoPlayer 组件 Source: https://github.com/agions/xfyun-sdk/blob/main/docs/DOCUMENT_DESIGN.md 在 Markdown 中使用 DemoPlayer 组件的示例。 ```markdown ::: demo ::: ``` -------------------------------- ### 首页设计 (VitePress home layout) Source: https://github.com/agions/xfyun-sdk/blob/main/docs/DOCUMENT_DESIGN.md VitePress 首页的 Markdown 配置,包含 hero 区域和功能特性列表。用于生成 xfyun-sdk 文档站点首页。 ```markdown --- layout: home title: xfyun-sdk titleTemplate: 科大讯飞语音 Web SDK hero: name: xfyun-sdk text: 科大讯飞语音 Web SDK tagline: 让语音交互更简单 image: src: /logo.svg alt: xfyun-sdk Logo actions: - theme: brand text: 快速开始 link: /guide/getting-started - theme: alt text: API 文档 link: /api/asr - theme: alt text: GitHub link: https://github.com/Agions/xfyun-sdk features: - icon: 🎤 title: 语音识别 details: 实时语音转文字,支持多种语言和方言 - icon: 🔊 title: 语音合成 details: 文本转语音,支持多种发音人和音频格式 - icon: 🌐 title: 语音翻译 details: 边说边译,支持 15+ 种语言互译 - icon: ⚡ title: 零依赖 details: 仅依赖 crypto-js,轻量级设计 - icon: 🛡️ title: 类型安全 details: 完整的 TypeScript 类型定义 - icon: 📦 title: 模块化 details: ASR/TTS/Translator 独立模块,按需引入 --- ``` -------------------------------- ### 本地开发环境变量文件 (.env.local) Source: https://github.com/agions/xfyun-sdk/blob/main/docs/guide/authentication.md 定义本地开发使用的讯飞 API 凭证环境变量,不会被提交到 Git。 ```env # .env.local VITE_XFYUN_APP_ID=your_dev_app_id VITE_XFYUN_API_KEY=your_dev_api_key VITE_XFYUN_API_SECRET=your_dev_api_secret ``` -------------------------------- ### isAudioFormatSupported() Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/utils.md 检查音频格式是否支持。接受音频格式字符串并返回布尔值。 ```APIDOC ## isAudioFormatSupported() ### Description 检查音频格式是否支持。 ### Request Example ```typescript import { isAudioFormatSupported } from 'xfyun-sdk'; const supported = isAudioFormatSupported('audio/L16;rate=16000'); console.log(supported); // true ``` ``` -------------------------------- ### 添加 .env 到 .gitignore Source: https://github.com/agions/xfyun-sdk/blob/main/docs/guide/authentication.md 防止环境变量文件被提交到版本控制系统。 ```gitignore # .gitignore .env .env.local .env.*.local ``` -------------------------------- ### 基础语音翻译:使用 createTranslator 进行语音翻译 Source: https://github.com/agions/xfyun-sdk/blob/main/docs/examples/translator-demo.md 使用 xfyun-sdk 的 createTranslator 创建语音翻译实例,配置 appId、apiKey、apiSecret 和翻译语言。监听 'result' 事件获取翻译结果,监听 'error' 事件处理错误。调用 start() 开始翻译,需要先获取麦克风权限。 ```typescript import { createTranslator } from 'xfyun-sdk'; const translator = createTranslator({ appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY', apiSecret: 'YOUR_API_SECRET', type: 'asr', // 语音翻译模式 from: 'cn', to: 'en', }); translator.on('result', (text, isFinal) => { console.log('翻译结果:', text); if (isFinal) { console.log('最终翻译:', text); } }); translator.on('error', (error) => { console.error('翻译错误:', error); }); async function startTranslation() { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); translator.start(); } ``` -------------------------------- ### stop() Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/asr.md Stops speech recognition. The WebSocket connection remains open, allowing subsequent calls to start() to resume recognition. ```APIDOC ## stop() ### Description Stops speech recognition. The WebSocket connection remains open, allowing subsequent calls to start() to resume recognition. ### Method stop ### Signature `recognizer.stop(): void` ``` -------------------------------- ### createWebSocket() Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/utils.md 创建 WebSocket 连接。接受 URL 和可选的配置对象(包含 protocols 和 headers)。 ```APIDOC ## createWebSocket() ### Description 创建 WebSocket 连接。 ### Request Example ```typescript import { createWebSocket } from 'xfyun-sdk'; const ws = createWebSocket('wss://example.com', { protocols: ['protocol1'], headers: { 'Authorization': 'Bearer token', }, }); ``` ``` -------------------------------- ### createWebSocket() 创建 WebSocket 连接 Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/utils.md 创建 WebSocket 连接,可指定 protocols 和 headers 选项。 ```typescript import { createWebSocket } from 'xfyun-sdk'; const ws = createWebSocket('wss://example.com', { protocols: ['protocol1'], headers: { 'Authorization': 'Bearer token', }, }); ``` -------------------------------- ### translator.start(text?) Source: https://github.com/agions/xfyun-sdk/blob/main/docs-dist/api/translator.html Starts the translation process. For text translation mode, the text parameter is required; for speech translation mode, it can be omitted. ```APIDOC ## translator.start(text?) ### Description Starts the translation process. For text translation mode, the text parameter is required; for speech translation mode, it can be omitted. ### Method start ### Parameters - `text` (string) - Optional - 翻译文本(文本翻译模式必填,语音翻译模式可省略) ### Response Returns a Promise that resolves when the translation starts. ``` -------------------------------- ### package.json 中的 VitePress 脚本配置 Source: https://github.com/agions/xfyun-sdk/blob/main/docs/DOCUMENT_DESIGN.md 定义 VitePress 文档的本地开发、构建和预览命令。需要 pnpm 作为包管理器。 ```json // package.json { "scripts": { "docs:dev": "vitepress dev docs", "docs:build": "vitepress build docs", "docs:preview": "vitepress preview docs" } } ``` -------------------------------- ### createTranslator Source: https://github.com/agions/xfyun-sdk/blob/main/docs-dist/api/translator.html Creates a translator instance for speech translation. The instance emits 'result' events with translated text and can be started to begin translation. ```APIDOC ## createTranslator ### Description Creates a translator instance for speech translation. The instance emits 'result' events with translated text and can be started to begin translation. ### Method Factory function ### Parameters #### Request Body - **appId** (string) - Required - Your application ID. - **apiKey** (string) - Required - Your API key. - **apiSecret** (string) - Required - Your API secret. - **type** (string) - Required - Set to 'asr' for speech translation mode. ### Response Returns a translator instance with methods `on` and `start`. ### Request Example ```typescript const translator = createTranslator({ appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY', apiSecret: 'YOUR_API_SECRET', type: 'asr', // 语音翻译模式 }); ``` ### Response Example ```typescript translator.on('result', (text) => { console.log('翻译结果:', text); }); translator.start(); ``` ``` -------------------------------- ### yarn 安装命令 Source: https://github.com/agions/xfyun-sdk/blob/main/docs-dist/DOCUMENT_DESIGN.html 使用 yarn 安装 xfyun-sdk 的命令。 ```bash yarn add xfyun-sdk ``` -------------------------------- ### XfyunTranslator (Instance) - Speech Translation Source: https://github.com/agions/xfyun-sdk/blob/main/README.md Instance-based speech translation (speak and translate). Configure the translator for speech recognition and translation, then start, stop, or destroy the session. ```APIDOC ## XfyunTranslator (Instance) - Speech Translation ### Description Instance-based speech translation (speak and translate). Configure the translator for speech recognition and translation, then start, stop, or destroy the session. ### Method Instance Method ### Constructor `new XfyunTranslator(config, callbacks)` ### Parameters #### config - **appId** (string) - Required - The Xfyun application ID. - **apiKey** (string) - Required - The Xfyun API key. - **apiSecret** (string) - Required - The Xfyun API secret. - **type** (string) - Required - Set to 'asr' for speech translation. - **from** (string) - Required - Source language code (e.g., 'cn' for Chinese). - **to** (string) - Required - Target language code (e.g., 'en' for English). - **domain** (string) - Required - Scenario domain (e.g., 'iner' for daily conversation). - **vadEos** (number) - Required - Silence detection timeout in milliseconds. #### callbacks - **onStart** (function) - Optional - Callback invoked when translation starts. - **onResult** (function) - Optional - Callback invoked with the translation result object. - **onEnd** (function) - Optional - Callback invoked when translation ends. ### Methods #### start() Starts the speech translation session. #### stop() Stops the speech translation session. #### destroy() Destroys the translator instance. ### Response #### onResult callback - **sourceText** (string) - The recognized source text. - **targetText** (string) - The translated text. - **isFinal** (boolean) - Indicates whether the result is final. ### Request Example ```javascript const translator = new XfyunTranslator( { appId: 'your_app_id', apiKey: 'your_api_key', apiSecret: 'your_api_secret', type: 'asr', // 语音翻译模式 from: 'cn', // 源语言:中文 to: 'en', // 目标语言:英文 domain: 'iner', // 场景:日常对话 vadEos: 5000, // 静音检测超时 }, { onStart: () => console.log('翻译开始'), onResult: (result) => { console.log('源文:', result.sourceText); console.log('译文:', result.targetText); console.log('是否最终:', result.isFinal); }, onEnd: () => console.log('翻译结束'), } ); // 开始语音翻译 translator.start(); // 停止翻译 translator.stop(); // 销毁实例 translator.destroy(); ``` ``` -------------------------------- ### After: 复用基类 BaseWebSocketClient Source: https://github.com/agions/xfyun-sdk/blob/main/docs/refactoring-report.md 重构后,所有类继承 BaseWebSocketClient,自动获得通用方法,子类只需实现特定逻辑。 ```typescript // 所有类继承 BaseWebSocketClient,自动获得这些方法 export abstract class BaseWebSocketClient<...> { protected ensureWebSocket(): WebSocket { ... } protected safeSend(data: string | ArrayBuffer): boolean { ... } protected safeCloseWebSocket(): void { ... } // ... 其他通用方法 } // 子类只需实现特定逻辑 export class XfyunASR extends BaseWebSocketClient<...> { protected parseMessage(data: string | ArrayBuffer): void { // ASR 特有的消息解析 } // ... } ``` -------------------------------- ### createTranslator Source: https://github.com/agions/xfyun-sdk/blob/main/docs-dist/api/translator.html Factory function to create a translator instance. Accepts options for configuration and returns a translator object with event methods and start functionality. ```APIDOC ## createTranslator ### Description Factory function to create a translator instance. Accepts options for configuration and returns a translator object with event methods and start functionality. ### Method `createTranslator` ### Parameters - **options** (XfyunTranslatorOptions) - Configuration options. - **appId** (string) - Application ID. - **apiKey** (string) - API key. - **apiSecret** (string) - API secret. - **type** (string) - Optional. Type of translation: 'asr' or 'text'. - **from** (SourceLanguage) - Optional. Source language code. - **to** (TargetLanguage) - Optional. Target language code. - **domain** (string) - Optional. Domain. - **autoStart** (boolean) - Optional. Whether to auto-start. - **vadEos** (number) - Optional. VAD end-of-speech threshold. - **sampleRate** (number) - Optional. Sample rate. - **logLevel** (string) - Optional. Log level: 'debug', 'info', 'warn', 'error'. ### Returns - **Translator** - A translator instance with methods `on`, `start`, etc. ### Example ```typescript import { createTranslator } from 'xfyun-sdk'; const translator = createTranslator({ appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY', apiSecret: 'YOUR_API_SECRET', type: 'asr', from: 'cn', to: 'en', }); translator.on('result', (text, isFinal) => { console.log('翻译结果:', text); if (isFinal) { console.log('最终翻译:', text); } }); translator.on('error', (error) => { console.error('翻译错误:', error); }); async function startTranslation() { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); translator.start(); } ``` ``` -------------------------------- ### Vue 3 TTS 组件 (Vue) Source: https://github.com/agions/xfyun-sdk/blob/main/docs/examples/tts-demo.md 一个 Vue 3 组件,使用 createSynthesizer 实现文本转语音,支持选择音色、播放和停止。通过 import.meta.env 读取环境变量作为凭证,监听 'start' 和 'complete' 事件更新播放状态。 ```vue ``` -------------------------------- ### 构造函数测试重复 (constructor) Source: https://github.com/agions/xfyun-sdk/blob/main/docs/code-duplication-analysis.md 三个测试文件中重复的构造函数测试,验证缺少必要参数时抛出错误,以及有效参数时创建实例。 ```typescript describe('constructor', () => { it('should throw error when required parameters are missing', () => { expect(() => new XfyunXXX({} as XfyunXXOptions)).toThrow('缺少必要参数'); expect(() => new XfyunXXX({ appId: 'test' } as XfyunXXOptions)).toThrow('缺少必要参数'); expect(() => new XfyunXXX({ appId: 'test', apiKey: 'test' } as XfyunXXOptions)).toThrow('缺少必要参数'); }); it('should create instance with valid parameters', () => { const options: XfyunXXOptions = { appId: 'test', apiKey: 'test', apiSecret: 'test' }; const instance = new XfyunXXX(options); expect(instance).toBeDefined(); expect(instance.getState()).toBe('idle'); }); }); ``` -------------------------------- ### Get current translator state Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/translator.md Returns the current state of the translator. Possible values: 'idle', 'connecting', 'connected', 'translating', 'stopped', or 'error'. ```typescript translator.getState(): TranslatorState ``` -------------------------------- ### getSupportedAudioFormats() 获取支持的音频格式列表 Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/utils.md 返回支持的音频格式数组,如 ['audio/L16;rate=16000', 'audio/L16;rate=8000', ...]。 ```typescript import { getSupportedAudioFormats } from 'xfyun-sdk'; const formats = getSupportedAudioFormats(); console.log(formats); // ['audio/L16;rate=16000', 'audio/L16;rate=8000', ...] ``` -------------------------------- ### createRecognizer Source: https://github.com/agions/xfyun-sdk/blob/main/docs/api/asr.md Creates a new speech recognition recognizer instance with the provided options. The recognizer can be used to start and stop recognition, and emits events for results and errors. ```APIDOC ## createRecognizer ### Description Creates a new speech recognition recognizer instance with the provided options. The recognizer can be used to start and stop recognition, and emits events for results and errors. ### Method Function ### Signature `createRecognizer(options: XfyunASROptions): Recognizer` ### Parameters #### Options (XfyunASROptions) - **appId** (string) - Required - The application ID for the Xfyun service. - **apiKey** (string) - Required - The API key for authentication. - **apiSecret** (string) - Required - The API secret for authentication. - **language** ('zh_cn' | 'en_us') - Optional - The recognition language. Default is 'zh_cn'. - **domain** ('iat' | 'medical' | 'assistant') - Optional - The recognition domain. Default is 'iat'. - **accent** ('mandarin' | 'cantonese') - Optional - The accent for recognition. - **vadEos** (number) - Optional - Voice activity detection end-of-speech timeout. - **maxAudioSize** (number) - Optional - Maximum audio size in bytes. - **autoStart** (boolean) - Optional - Whether to start recognition automatically. - **hotWords** (string[]) - Optional - List of hot words to boost recognition. - **punctuation** (boolean | string) - Optional - Whether to add punctuation or a custom punctuation string. - **audioFormat** (string) - Optional - The audio format. - **reconnectAttempts** (number) - Optional - Number of reconnection attempts. - **reconnectInterval** (number) - Optional - Interval between reconnection attempts. - **enableReconnect** (boolean) - Optional - Whether to enable reconnection. - **logLevel** ('debug' | 'info' | 'warn' | 'error') - Optional - Logging level. ### Returns - **Recognizer** - An object with methods `start()`, `stop()`, and event handlers like `on(event, callback)`. ### Example ```typescript const recognizer = createRecognizer({ appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY', apiSecret: 'YOUR_API_SECRET', }); recognizer.on('result', (text) => { console.log(text); }); recognizer.start(); ``` ``` -------------------------------- ### 推送代码和标签到 GitHub Source: https://github.com/agions/xfyun-sdk/blob/main/RELEASE_GUIDE.md 推送代码和 v1.4.0 标签到远程仓库。 ```bash cd /home/agentuser/.openclaw/workspace/xfyun-sdk # 推送代码 git push origin main # 推送 tag git push origin v1.4.0 ``` -------------------------------- ### Use composable useSpeechRecognizer Source: https://github.com/agions/xfyun-sdk/blob/main/examples/vue-demo/README.md Recommended way to integrate speech recognition. Import the composable, pass your API credentials and options, then call start() and stop() to control recognition. ```typescript import { useSpeechRecognizer } from '@/composables/useSpeechRecognizer'; const { isListening, transcript, error, volume, state, start, stop } = useSpeechRecognizer({ appId: 'your_app_id', apiKey: 'your_api_key', apiSecret: 'your_api_secret', language: 'zh_cn', accent: 'mandarin', }); // 开始识别 await start(); // 停止识别 stop(); ```