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 = 2倍の速度(速い)
- 音量範囲: 0より大きく、最大10
- デフォルト: 1.0
- 値は0(除外)より大きく、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 を使用する場合:
- アプリケーション内での動的な音声生成
- Web サービスとの統合
- カスタムオーディオ処理パイプライン
- 複雑な要件を持つプロダクションアプリケーション
基本的な 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 オブジェクトから array buffer を取得
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(new Uint8Array(arrayBuffer));
fs.writeFileSync(outputPath, buffer);
console.log(`Audio saved to ${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 オブジェクトから array buffer を取得
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 = 2倍の速度(速い)
// この範囲外の値は API エラーを引き起こします
const response = await zai.audio.tts.create({
input: text,
voice: 'tongtong',
speed: speed,
response_format: 'wav',
stream: false
});
// Response オブジェクトから array buffer を取得
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(除外)かつ <= 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 オブジェクトから array buffer を取得
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 オブジェクトから array buffer を取得
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('Generated:', results.length, 'audio files');
動的コンテンツ生成
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 オブジェクトから array buffer を取得
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 オブジェクトから array buffer を取得
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('Text input cannot be empty');
}
if (text.length > 1024) {
throw new Error('Text input exceeds maximum length of 1024 characters');
}
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 オブジェクトから array buffer を取得
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({ ... });
一般的なユースケース
- オーディオブック & ポッドキャスト: 書かれたコンテンツをオーディオ形式に変換
- Eラーニング: 教育コンテンツのナレーションを作成
- アクセシビリティ: テキストコンテンツの音声版を提供
- 音声アシスタント: 動的な応答を生成
- アナウンス: 自動音声通知を作成
- 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(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
}
initZAI().catch(console.error);
app.post('/api/tts', async (req, res) => {
try {
const {
text,
voice = 'tongtong',
speed = 1.0,
format = 'wav'
} = req.body;
if (!text) {
return res.status(400).json({ error: 'Text フィールドは必須です' });
}
const response = await zaiInstance.audio.tts.create({
input: text,
voice: voice,
speed: speed,
response_format: format,
stream: false
});
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(new Uint8Array(arrayBuffer));
const contentType = format === 'mp3' ? 'audio/mpeg' :
format === 'pcm' ? 'audio/l16' : 'audio/wav';
res.setHeader('Content-Type', contentType);
res.setHeader('Content-Length', buffer.length);
res.send(buffer);
} catch (error) {
console.error('TTS Route Error:', error);
res.status(500).json({ error: '音声生成に失敗しました' });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`TTS サーバーがポート ${PORT} で起動しました`);
});
トラブルシューティング
よくある問題
-
応答がない
- テキスト入力が空でないことを確認
- テキスト長が1024文字を超えていないか確認
- ネットワーク接続をチェック
-
音質が悪い
- テキストに特殊文字や記号がないか確認
- 適切な音声モデルを使用しているか確認
- 速度設定を調整(1.0~1.5推奨)
-
ファイル形式の問題
- ストリーミングを使用する場合は pcm 形式のみサポートされることに注意
- 適切なファイル拡張子を使用(.wav、.mp3、.pcm)
-
音量の問題
- 音量値が0より大きく10以下であることを確認
- 値が範囲外の場合、APIはエラーを返す