TTS(文字轉語音)技能
此技能引導使用 z-ai-web-dev-sdk 套件實作文字轉語音 (TTS) 功能,將文字轉換為自然流暢的語音音訊。
技能路徑
技能位置:{project_path}/skills/TTS
此技能位於專案中的上述路徑。
參考腳本:可在 {Skill Location}/scripts/ 目錄中找到測試腳本範例,用於快速測試與參考。請參閱 {Skill Location}/scripts/tts.ts 查看實際運作範例。
概覽
文字轉語音可讓您建立能從文字輸入產生口語音訊的應用程式,支援多種語音、語速與輸出格式,以滿足多樣化的使用情境。
重要事項:z-ai-web-dev-sdk 必須僅在後端程式碼中使用。切勿在客戶端程式碼中使用。
API 限制與限制條件
在實作 TTS 功能之前,請注意以下重要限制:
輸入文字限制
- 最大長度:每則請求 1024 個字元
- 超出此限制的文字必須分割成較小的區塊
音訊參數
- 語速範圍:0.5 至 2.0
- 0.5 = 半速(較慢)
- 1.0 = 正常速度(預設)
- 2.0 = 雙倍速度(較快)
- 音量範圍:大於 0,最高至 10
- 預設值:1.0
- 數值必須大於 0(不包含 0)且小於等於 10(包含 10)
格式與串流
- 串流限制:啟用
stream: true時,僅支援pcm格式 - 非串流:支援
wav、pcm和mp3格式 - 取樣率:24000 Hz(建議使用)
長文字的最佳作法
function splitTextIntoChunks(text, maxLength = 1000) {
const chunks = [];
const sentences = text.match(/[^.!?]+[.!?]+/g) || [text];
let currentChunk = '';
for (const sentence of sentences) {
if ((currentChunk + sentence).length <= maxLength) {
currentChunk += sentence;
} else {
if (currentChunk) chunks.push(currentChunk.trim());
currentChunk = sentence;
}
}
if (currentChunk) chunks.push(currentChunk.trim());
return chunks;
}
先決條件
z-ai-web-dev-sdk 套件已安裝完畢。請依照以下範例所示方式匯入。
CLI 使用方式(適用於簡單任務)
對於簡單的文字轉語音轉換,您可以使用 z-ai CLI 代替編寫程式碼。這適合快速產生音訊、測試語音或簡單的自動化作業。
基本 TTS
# 將文字轉換為語音(預設 WAV 格式)
z-ai tts --input "Hello, world" --output ./hello.wav
# 使用短選項
z-ai tts -i "Hello, world" -o ./hello.wav
不同語音與語速
# 使用特定語音
z-ai tts -i "Welcome to our service" -o ./welcome.wav --voice tongtong
# 調整語速 (0.5-2.0)
z-ai tts -i "This is faster speech" -o ./fast.wav --speed 1.5
# 較慢的語速
z-ai tts -i "This is slower speech" -o ./slow.wav --speed 0.8
不同輸出格式
# MP3 格式
z-ai tts -i "Hello World" -o ./hello.mp3 --format mp3
# WAV 格式(預設)
z-ai tts -i "Hello World" -o ./hello.wav --format wav
# PCM 格式
z-ai tts -i "Hello World" -o ./hello.pcm --format pcm
串流輸出
# 串流音訊產生
z-ai tts -i "This is a longer text that will be streamed" -o ./stream.wav --stream
CLI 參數
--input, -i <text>:必要 - 要轉換為語音的文字(最多 1024 個字元)--output, -o <path>:必要 - 輸出音訊檔案路徑--voice, -v <voice>:選用 - 語音類型(預設:tongtong)--speed, -s <number>:選用 - 語速,0.5-2.0(預設:1.0)--format, -f <format>:選用 - 輸出格式:wav、mp3、pcm(預設:wav)--stream:選用 - 啟用串流輸出(僅支援 pcm 格式)
何時使用 CLI 與 SDK
使用 CLI 時機:
- 快速進行文字轉語音轉換
- 測試不同語音與語速
- 簡單的批次音訊產生
- 命令列自動化腳本
使用 SDK 時機:
- 應用程式中的動態音訊產生
- 與網頁服務整合
- 自訂音訊處理管道
- 具有複雜需求的正式應用程式
基本 TTS 實作
簡單的文字轉語音
import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';
async function textToSpeech(text, outputPath) {
const zai = await ZAI.create();
const response = await zai.audio.tts.create({
input: text,
voice: 'tongtong',
speed: 1.0,
response_format: 'wav',
stream: false
});
// 從 Response 物件取得陣列緩衝區
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(new Uint8Array(arrayBuffer));
fs.writeFileSync(outputPath, buffer);
console.log(`音訊已儲存至 ${outputPath}`);
return outputPath;
}
// 使用方式
await textToSpeech('Hello, world!', './output.wav');
多種語音選項
import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';
async function generateWithVoice(text, voice, outputPath) {
const zai = await ZAI.create();
const response = await zai.audio.tts.create({
input: text,
voice: voice, // 可用語音:tongtong、chuichui、xiaochen、jam、kazi、douji、luodo
speed: 1.0,
response_format: 'wav',
stream: false
});
// 從 Response 物件取得陣列緩衝區
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(new Uint8Array(arrayBuffer));
fs.writeFileSync(outputPath, buffer);
return outputPath;
}
// 使用方式
await generateWithVoice('Welcome to our service', 'tongtong', './welcome.wav');
可調整語速
import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';
async function generateWithSpeed(text, speed, outputPath) {
const zai = await ZAI.create();
// 語速範圍:0.5 至 2.0(API 限制)
// 0.5 = 半速(較慢)
// 1.0 = 正常速度(預設)
// 2.0 = 雙倍速度(較快)
// 超出此範圍的數值會導致 API 錯誤
const response = await zai.audio.tts.create({
input: text,
voice: 'tongtong',
speed: speed,
response_format: 'wav',
stream: false
});
// 從 Response 物件取得陣列緩衝區
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(new Uint8Array(arrayBuffer));
fs.writeFileSync(outputPath, buffer);
return outputPath;
}
// 使用方式 - 較慢的旁白
await generateWithSpeed('This is an important announcement', 0.8, './slow.wav');
// 使用方式 - 較快的旁白
await generateWithSpeed('Quick update', 1.3, './fast.wav');
可調整音量
import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';
async function generateWithVolume(text, volume, outputPath) {
const zai = await ZAI.create();
// 音量範圍:大於 0,最高至 10(API 限制)
// 數值必須 > 0(不包含 0)且 <= 10(包含 10)
// 預設值:1.0(正常音量)
const response = await zai.audio.tts.create({
input: text,
voice: 'tongtong',
speed: 1.0,
volume: volume, // 選用參數
response_format: 'wav',
stream: false
});
// 從 Response 物件取得陣列緩衝區
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(new Uint8Array(arrayBuffer));
fs.writeFileSync(outputPath, buffer);
return outputPath;
}
// 使用方式 - 較大聲的音訊
await generateWithVolume('This is an announcement', 5.0, './loud.wav');
// 使用方式 - 較小聲的音訊
await generateWithVolume('Whispered message', 0.5, './quiet.wav');
進階使用案例
批次處理
import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';
import path from 'path';
async function batchTextToSpeech(textArray, outputDir) {
const zai = await ZAI.create();
const results = [];
// 確保輸出目錄存在
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
for (let i = 0; i < textArray.length; i++) {
try {
const text = textArray[i];
const outputPath = path.join(outputDir, `audio_${i + 1}.wav`);
const response = await zai.audio.tts.create({
input: text,
voice: 'tongtong',
speed: 1.0,
response_format: 'wav',
stream: false
});
// 從 Response 物件取得陣列緩衝區
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(new Uint8Array(arrayBuffer));
fs.writeFileSync(outputPath, buffer);
results.push({
success: true,
text,
path: outputPath
});
} catch (error) {
results.push({
success: false,
text: textArray[i],
error: error.message
});
}
}
return results;
}
// 使用方式
const texts = [
'Welcome to chapter one',
'Welcome to chapter two',
'Welcome to chapter three'
];
const results = await batchTextToSpeech(texts, './audio-output');
console.log('已產生:', results.length, '個音訊檔案');
動態內容產生
import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';
class TTSGenerator {
constructor() {
this.zai = null;
}
async initialize() {
this.zai = await ZAI.create();
}
async generateAudio(text, options = {}) {
const {
voice = 'tongtong',
speed = 1.0,
format = 'wav'
} = options;
const response = await this.zai.audio.tts.create({
input: text,
voice: voice,
speed: speed,
response_format: format,
stream: false
});
// 從 Response 物件取得陣列緩衝區
const arrayBuffer = await response.arrayBuffer();
return Buffer.from(new Uint8Array(arrayBuffer));
}
async saveAudio(text, outputPath, options = {}) {
const buffer = await this.generateAudio(text, options);
if (buffer) {
fs.writeFileSync(outputPath, buffer);
return outputPath;
}
return null;
}
}
// 使用方式
const generator = new TTSGenerator();
await generator.initialize();
await generator.saveAudio(
'Hello, this is a test',
'./output.wav',
{ speed: 1.2 }
);
Next.js API 路由範例
import { NextRequest, NextResponse } from 'next/server';
export async function POST(req: NextRequest) {
try {
const { text, voice = 'tongtong', speed = 1.0 } = await req.json();
// 匯入 ZAI SDK
const ZAI = (await import('z-ai-web-dev-sdk')).default;
// 建立 SDK 實例
const zai = await ZAI.create();
// 產生 TTS 音訊
const response = await zai.audio.tts.create({
input: text.trim(),
voice: voice,
speed: speed,
response_format: 'wav',
stream: false,
});
// 從 Response 物件取得陣列緩衝區
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(new Uint8Array(arrayBuffer));
// 以音訊作為回應
return new NextResponse(buffer, {
status: 200,
headers: {
'Content-Type': 'audio/wav',
'Content-Length': buffer.length.toString(),
'Cache-Control': 'no-cache',
},
});
} catch (error) {
console.error('TTS API Error:', error);
return NextResponse.json(
{
error: error instanceof Error ? error.message : '生成語音失敗,請稍後重試',
},
{ status: 500 }
);
}
}
最佳作法
1. 文字預處理
function prepareTextForTTS(text) {
// 移除過多的空白
text = text.replace(/\s+/g, ' ').trim();
// 展開常見縮寫以獲得更好的發音
const abbreviations = {
'Dr.': 'Doctor',
'Mr.': 'Mister',
'Mrs.': 'Misses',
'etc.': 'et cetera'
};
for (const [abbr, full] of Object.entries(abbreviations)) {
text = text.replace(new RegExp(abbr, 'g'), full);
}
return text;
}
2. 錯誤處理
import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';
async function safeTTS(text, outputPath) {
try {
// 驗證輸入
if (!text || text.trim().length === 0) {
throw new Error('文字輸入不可為空');
}
if (text.length > 1024) {
throw new Error('文字輸入超過最大長度 1024 個字元');
}
const zai = await ZAI.create();
const response = await zai.audio.tts.create({
input: text,
voice: 'tongtong',
speed: 1.0,
response_format: 'wav',
stream: false
});
// 從 Response 物件取得陣列緩衝區
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(new Uint8Array(arrayBuffer));
fs.writeFileSync(outputPath, buffer);
return {
success: true,
path: outputPath,
size: buffer.length
};
} catch (error) {
console.error('TTS Error:', error);
return {
success: false,
error: error.message
};
}
}
3. SDK 實例重複使用
import ZAI from 'z-ai-web-dev-sdk';
// 建立單例實例
let zaiInstance = null;
async function getZAIInstance() {
if (!zaiInstance) {
zaiInstance = await ZAI.create();
}
return zaiInstance;
}
// 使用方式
const zai = await getZAIInstance();
const response = await zai.audio.tts.create({ ... });
常見使用案例
- 有聲書與播客:將書面內容轉換為音訊格式
- 電子學習:為教育內容建立旁白
- 無障礙功能:提供文字內容的音訊版本
- 語音助手:產生動態回應
- 公告通知:建立自動化音訊通知
- IVR 系統:產生電話系統提示音
- 內容本地化:以不同語言建立音訊
整合範例
Express.js API 端點
import express from 'express';
import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';
import path from 'path';
const app = express();
app.use(express.json());
let zaiInstance;
const outputDir = './audio-output';
async function initZAI() {
zaiInstance = await ZAI.create();
if (!fs.existsSync(o
…
[已截斷以進行翻譯]