// "prepublishOnly": "npm run build"
{以下是 Gitee 平台说明,您可以替换此简介 Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台 无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 https://gitee.com/enterprises}
软件架构说明
一、创建NPM包项目
- 初始化项目 bash Copy Code mkdir aliyun-voice-service cd aliyun-voice-service npm init -y
- 安装依赖 bash Copy Code npm install @alicloud/dyvmsapi20170525 @alicloud/openapi-client @alicloud/tea-util @alicloud/tea-typescript --save npm install typescript @types/node --save-dev
- 配置TypeScript 创建 tsconfig.json:
json Copy Code { "compilerOptions": { "target": "ES2019", "module": "CommonJS", "outDir": "dist", "rootDir": "src", "strict": true, "esModuleInterop": true, "skipLibCheck": true } } 二、编写动态传参的NPM包代码
- 创建源码目录和文件 bash Copy Code mkdir src touch src/index.ts
- 代码实现 (src/index.ts) typescript Copy Code import Dyvmsapi20170525, * as $Dyvmsapi20170525 from '@alicloud/dyvmsapi20170525'; import OpenApi, * as $OpenApi from '@alicloud/openapi-client'; import Util, * as $Util from '@alicloud/tea-util'; import * as $tea from '@alicloud/tea-typescript';
// 定义配置接口 export interface AliyunVoiceConfig { accessKeyId: string; accessKeySecret: string; endpoint?: string; // 可选,默认 dyvmsapi.aliyuncs.com }
// 定义语音呼叫参数接口 export interface VoiceCallParams { calledNumber: string; // 被叫号码 ttsCode: string; // TTS模板ID ttsParam?: Record<string, string>; // 模板参数(可选) calledShowNumber?: string; // 显号(可选) }
export class AliyunVoiceClient { private client: Dyvmsapi20170525;
constructor(config: AliyunVoiceConfig) { // 初始化阿里云客户端 const openApiConfig = new $OpenApi.Config({ accessKeyId: config.accessKeyId, accessKeySecret: config.accessKeySecret, endpoint: config.endpoint || 'dyvmsapi.aliyuncs.com', }); this.client = new Dyvmsapi20170525(openApiConfig); }
/**
- 发起语音呼叫
- @param params 呼叫参数
- @returns 请求ID */ async makeVoiceCall(params: VoiceCallParams): Promise { const request = new $Dyvmsapi20170525.SingleCallByTtsRequest({ calledNumber: params.calledNumber, ttsCode: params.ttsCode, ttsParam: JSON.stringify(params.ttsParam || {}), calledShowNumber: params.calledShowNumber, });
try {
const runtime = new $Util.RuntimeOptions({});
const response = await this.client.singleCallByTtsWithOptions(request, runtime);
return response.body.requestId;
} catch (error) {
throw new Error(`语音呼叫失败: ${error.message}`);
}
} } 三、构建和发布包
- 添加构建脚本 在 package.json 中添加:
json Copy Code { "scripts": { "build": "tsc", "prepublishOnly": "npm run build" }, "main": "dist/index.js", "types": "dist/index.d.ts" } 2. 构建项目 bash Copy Code npm run build 3. 发布到NPM bash Copy Code npm publish 四、在其他项目中引用
- 安装包 bash Copy Code npm install aliyun-voice-service
- 使用示例 typescript Copy Code import { AliyunVoiceClient, VoiceCallParams } from 'aliyun-voice-service';
// 初始化客户端 const voiceClient = new AliyunVoiceClient({ accessKeyId: 'YOUR_ACCESS_KEY_ID', accessKeySecret: 'YOUR_ACCESS_KEY_SECRET', });
// 发起语音呼叫 async function testCall() { const params: VoiceCallParams = { calledNumber: '13800138000', // 被叫号码 ttsCode: 'TTS_12345678', // 模板ID ttsParam: { name: "张三", code: "1234" }, // 动态模板参数 calledShowNumber: '01088888888' // 显号 };
try { const requestId = await voiceClient.makeVoiceCall(params); console.log('呼叫成功,请求ID:', requestId); } catch (err) { console.error('呼叫失败:', err.message); } }
testCall(); 五、关键功能说明 动态配置:
通过构造函数接收 accessKeyId 和 accessKeySecret 可自定义阿里云API的 endpoint 灵活传参:
calledNumber: 动态传入被叫号码 ttsCode: 指定不同的语音模板 ttsParam: 支持JSON格式的动态模板参数 calledShowNumber: 可自定义显号 错误处理:
封装了阿里云SDK的异常,抛出友好错误信息 六、最佳实践建议 敏感信息管理:
typescript Copy Code // 从环境变量读取(推荐) const voiceClient = new AliyunVoiceClient({ accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID, accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET, }); 添加重试机制:
typescript Copy Code async function makeVoiceCallWithRetry(params: VoiceCallParams, retries = 3) { for (let i = 0; i < retries; i++) { try { return await this.makeVoiceCall(params); } catch (err) { if (i === retries - 1) throw err; await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))); } } } 日志记录:
在关键节点添加日志输出 记录每次呼叫的请求ID和被叫号码
- xxxx
- xxxx
- xxxx
- Fork 本仓库
- 新建 Feat_xxx 分支
- 提交代码
- 新建 Pull Request
- 使用 Readme_XXX.md 来支持不同的语言,例如 Readme_en.md, Readme_zh.md
- Gitee 官方博客 blog.gitee.com
- 你可以 https://gitee.com/explore 这个地址来了解 Gitee 上的优秀开源项目
- GVP 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
- Gitee 官方提供的使用手册 https://gitee.com/help
- Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 https://gitee.com/gitee-stars/