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(`オーディオを ${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('生成されたオーディオファイル数:', 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 オブジェクトから 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);
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 オブジェクトから 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);
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();
app.post('/api/tts', async (req, res) => {
try {
const { text, voice = 'tongtong', speed = 1.0, format = 'wav' } = req.body;
if (!text || text.trim().length === 0) {
return res.status(400).json({ error: 'テキスト入力が必要です' });
}
if (text.length > 1024) {
return res.status(400).json({ error: 'テキストが長すぎます (最大 1024 文字)' });
}
const response = await zaiInstance.audio.tts.create({
input: text.trim(),
voice: voice,
speed: speed,
response_format: format,
stream: false
});
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(new Uint8Array(arrayBuffer));
const filename = `tts_${Date.now()}.${format}`;
const filePath = path.join(outputDir, filename);
fs.writeFileSync(filePath, buffer);
res.json({
success: true,
filename: filename,
path: filePath,
size: buffer.length,
format: format
});
} catch (error) {
console.error('TTS エラー:', error);
res.status(500).json({ error: '音声生成に失敗しました', details: error.message });
}
});
app.listen(3001, () => {
console.log('TTS サーバーがポート 3001 で起動しました');
});