web端接入 科大讯飞语音合成 (kdxf-tts)

413 阅读3分钟

简介

科大讯飞语音合成(TTS)模块,封装了科大讯飞在线语音合成WebSocket接口,可轻松实现文本到语音的转换功能。支持自定义音色、语速、音量等参数。

安装

# npm
npm install kdxf-tts
​
# yarn
yarn add kdxf-tts 
​
# pnpm
pnpm add kdxf-tts

基本使用

普通JS项目

import { createTtsClient } from 'kdxf-tts';
​
// 创建TTS实例
const tts = createTtsClient({
  appid: "您的科大讯飞APPID", 
  apiKey: "您的APIKey",
  apiSecret: "您的APISecret"
});
​
// 合成并播放
tts.play("您好,这是一段测试文本");
​
// 设置回调函数
tts.onTtsStart = () => {
  console.log("开始合成");
};
​
tts.onTtsEnd = () => {
  console.log("合成结束");
};

在Vue项目中使用

在组件中使用

<template>
  <div class="tts-demo">
    <div class="input-area">
      <textarea 
        v-model="text" 
        placeholder="请输入要合成的文本"
        rows="5"
      ></textarea>
    </div>
    
    <div class="controls">
      <select v-model="voice" @change="updateVoice">
        <option value="xiaoyan">小燕</option>
        <option value="aisjiuxu">许久</option>
        <option value="aisxping">小萍</option>
      </select>
      
      <button @click="playText" :disabled="isPlaying">播放</button>
      <button @click="stopPlay" :disabled="!isPlaying">停止</button>
    </div>
    
    <div v-if="isProcessing" class="status">
      正在合成...
    </div>
    
    <div v-if="isPlaying" class="progress-area">
      <progress :value="progress" max="100"></progress>
      <span>{{ Math.round(progress) }}%</span>
    </div>
  </div>
</template><script>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { createTtsClient } from 'kdxf-tts';
​
export default {
  name: 'TtsDemo',
  
  setup() {
    const text = ref('');
    const voice = ref('xiaoyan');
    const isProcessing = ref(false);
    const isPlaying = ref(false);
    const progress = ref(0);
    
    let ttsClient = null;
    
    onMounted(() => {
      // 初始化TTS客户端
      ttsClient = createTtsClient({
        appid: 'YOUR_APPID', 
        apiKey: 'YOUR_API_KEY',
        apiSecret: 'YOUR_API_SECRET',
        voiceName: voice.value
      });
      
      // 设置回调
      ttsClient.onTtsStart = () => {
        isProcessing.value = true;
      };
      
      ttsClient.onTtsEnd = () => {
        isProcessing.value = false;
        isPlaying.value = false;
        progress.value = 0;
      };
      
      ttsClient.onTtsError = (error) => {
        console.error('TTS错误:', error);
        isProcessing.value = false;
        isPlaying.value = false;
      };
      
      ttsClient.onTtsPlaying = (p) => {
        progress.value = p;
        isPlaying.value = true;
      };
    });
    
    onBeforeUnmount(() => {
      // 组件销毁前停止播放
      if (ttsClient) {
        ttsClient.stopPlay();
      }
    });
    
    // 播放文本
    const playText = () => {
      if (!text.value || !ttsClient) return;
      
      ttsClient.play(text.value);
    };
    
    // 停止播放
    const stopPlay = () => {
      if (ttsClient) {
        ttsClient.stopPlay();
      }
    };
    
    // 更新语音参数
    const updateVoice = () => {
      if (ttsClient) {
        ttsClient.updateOptions({
          voiceName: voice.value
        });
      }
    };
    
    return {
      text,
      voice,
      isProcessing,
      isPlaying,
      progress,
      playText,
      stopPlay,
      updateVoice
    };
  }
}
</script><style scoped>
.tts-demo {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}
​
.input-area textarea {
  width: 100%;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}
​
.controls {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}
​
.controls button {
  padding: 8px 15px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
​
.controls button:disabled {
  background: #a0cfff;
  cursor: not-allowed;
}
​
.controls select {
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}
​
.status {
  margin-top: 15px;
  color: #409eff;
}
​
.progress-area {
  margin-top: 15px;
}
​
.progress-area progress {
  width: 100%;
  height: 20px;
}
</style>

创建插件(Vue 3)

可以将TTS客户端封装为Vue插件,方便在整个应用中使用:

// src/plugins/tts.js
import { createTtsClient } from 'kdxf-tts';
​
export default {
  install: (app, options) => {
    const ttsClient = createTtsClient({
      appid: options.appid || '',
      apiKey: options.apiKey || '',
      apiSecret: options.apiSecret || '',
      ...options
    });
    
    // 添加到全局属性
    app.config.globalProperties.$tts = ttsClient;
    
    // 提供给组合式API使用
    app.provide('tts', ttsClient);
  }
};

在main.js中注册插件:

// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import TtsPlugin from './plugins/tts.js';
​
const app = createApp(App);
​
app.use(TtsPlugin, {
  appid: 'YOUR_APPID',
  apiKey: 'YOUR_API_KEY',
  apiSecret: 'YOUR_API_SECRET',
  voiceName: 'xiaoyan'
});
​
app.mount('#app');

在组件中使用:

<template>
  <button @click="speak">播放语音</button>
</template><script>
import { inject } from 'vue';
​
export default {
  setup() {
    // 通过inject获取tts实例
    const tts = inject('tts');
    
    const speak = () => {
      tts.play('这是通过Vue插件调用的语音合成');
    };
    
    return { speak };
  }
}
</script>

或使用选项式API:

<template>
  <button @click="speak">播放语音</button>
</template><script>
export default {
  methods: {
    speak() {
      this.$tts.play('这是通过Vue插件调用的语音合成');
    }
  }
}
</script>

配置参数

创建TTS实例时,可以传入以下配置参数:

参数名说明默认值可选值
appid科大讯飞应用ID必填-
apiKeyAPI密钥必填-
apiSecretAPI密钥必填-
voiceName发音人"xiaoyan"xiaoyan, aisjiuxu, aisxping等
speed语速500-100
volume音量500-100
pitch音高500-100
audioType音频格式"mp3"mp3, wav, pcm
sampleRate采样率160008000, 16000

API参考

方法

play(text)

合成并播放文本。

tts.play("您好,这是语音合成测试");

stopPlay()

停止当前播放。

tts.stopPlay();

updateOptions(options)

更新配置参数。

tts.updateOptions({
  voiceName: "aisjiuxu",
  speed: 60,
  volume: 70
});

事件回调

onTtsStart

合成开始时触发。

tts.onTtsStart = () => {
  console.log("开始合成");
};

onTtsEnd

合成结束时触发。

tts.onTtsEnd = () => {
  console.log("合成结束");
};

onTtsError

发生错误时触发。

tts.onTtsError = (error) => {
  console.error("合成错误:", error);
};

onTtsPlaying

播放进度更新时触发。

tts.onTtsPlaying = (progress) => {
  console.log("播放进度:", progress + "%");
};

注意事项

  1. 使用前需要在科大讯飞开放平台注册账号并创建应用,获取APPID、APIKey和APISecret。
  2. 需要保证网络连接正常,因为该模块通过WebSocket与科大讯飞服务器通信。
  3. 浏览器环境中需要支持WebSocket和Audio API。
  4. 处理较长文本时,建议将文本分段处理。

常见问题

Q: 如何获取科大讯飞的APPID、APIKey和APISecret?

A: 登录科大讯飞开放平台,创建应用后在控制台获取相关凭证信息。

Q: 在Vue 2项目中如何使用?

A: Vue 2的使用方式与Vue 3类似,但插件安装方式略有不同:

// 插件定义
const TtsPlugin = {
  install(Vue, options) {
    const tts = createTtsClient(options);
    Vue.prototype.$tts = tts;
  }
};

// 安装
Vue.use(TtsPlugin, {
  appid: 'YOUR_APPID',
  apiKey: 'YOUR_API_KEY',
  apiSecret: 'YOUR_API_SECRET'
});

Q: 支持在Node.js环境使用吗?

A: 该模块主要设计用于浏览器环境,依赖WebSocket和Audio API。在Node.js环境中使用需要额外的适配。

许可证

MIT