> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# 用法 - VOICEVOX Core for PHP

> VOICEVOX Core for PHP 的基本用法。介绍文本朗读（TTS）与语音合成的代码示例。

## 基本的语音合成

以下 `talk.php` 是从文本合成音频并写入 WAV 文件的示例。

<Warning>
  PHP FFI 在 Web 服务器环境（如 FPM）中通常是禁用的。请像 `php talk.php` 这样 **从 CLI 中执行** 该脚本。
</Warning>

```php theme={null}
<?php

require __DIR__ . '/vendor/autoload.php';

use Revolution\Voicevox\Core\Enums\AccelerationMode;
use Revolution\Voicevox\Core\Onnxruntime;
use Revolution\Voicevox\Core\OpenJtalk;
use Revolution\Voicevox\Core\Synthesizer;
use Revolution\Voicevox\Core\VoiceModelFile;

// 请根据 voicevox_core 的安装位置修改路径
$voicevoxCoreDir = getenv('HOME') . '/.local/voicevox_core';
$onnxruntimeFilename = $voicevoxCoreDir . '/onnxruntime/lib/' . Onnxruntime::libVersionedFilename();
$dictDir = $voicevoxCoreDir . '/dict/open_jtalk_dic_utf_8-1.11';
$vvmPath  = $voicevoxCoreDir . '/models/vvms/0.vvm';

// 要合成的文本与 Style ID
$text    = 'この音声は、ボイスボックスを使用して、出力されています。';
$styleId = 0;
$outPath = './output.wav';

// 初始化
$onnxruntime = Onnxruntime::loadOnce($onnxruntimeFilename);
$openJtalk   = new OpenJtalk($dictDir);
$synthesizer = new Synthesizer($onnxruntime, $openJtalk, AccelerationMode::Auto);

// 加载语音模型
$model = VoiceModelFile::open($vvmPath);
$synthesizer->loadVoiceModel($model);

// 语音合成
$audioQuery = $synthesizer->createAudioQuery($text, $styleId);
$wav        = $synthesizer->synthesis($audioQuery, $styleId);

file_put_contents($outPath, $wav);
echo 'Wrote ' . $outPath . PHP_EOL;
```

执行：

```bash theme={null}
php talk.php
```

## 一步完成语音合成（`tts` 方法）

若想省略 `createAudioQuery` + `synthesis` 的两步流程，可以使用 `tts()` 方法：

```php theme={null}
$wav = $synthesizer->tts($text, $styleId);
file_put_contents('./output.wav', $wav);
```

## 通过片假名记法合成

也可以从 AquesTalk 风格的片假名记法进行合成：

```php theme={null}
// 使用 ttsFromKana 时
$wav = $synthesizer->ttsFromKana("コノオンセイワ'、ボイスボックスオ'/シヨーシテ'、シュツリョクサレテイマ'ス。", $styleId);
file_put_contents('./output.wav', $wav);
```

## 使用用户词典

要注册自定义词的读音，请使用 `UserDict`：

```php theme={null}
use Revolution\Voicevox\Core\UserDict;
use Revolution\Voicevox\Core\Enums\UserDictWordType;

$userDict = new UserDict();
$uuid = $userDict->addWord(
    surface: 'ボイボ',
    pronunciation: 'ボイボ',
    accentType: 0,
    wordType: UserDictWordType::ProperNoun,
    priority: 10,
);

// 保存词典
$userDict->save('./mydict.json');

// 将词典应用于 OpenJTalk
$openJtalk->useUserDict($userDict);
```

## 调整 AudioQuery

通过对 `createAudioQuery` 获得的 JSON 进行调整后再合成，可以对抑扬、节奏等做精细控制：

```php theme={null}
$audioQueryJson = $synthesizer->createAudioQuery($text, $styleId);

// 解码 JSON 并调整
$audioQuery = json_decode($audioQueryJson, true);
$audioQuery['speedScale'] = 1.2;   // 将速度调至 1.2 倍
$audioQuery['pitchScale'] = 0.05;  // 稍微提高音高

$wav = $synthesizer->synthesis(json_encode($audioQuery), $styleId);
file_put_contents('./output.wav', $wav);
```

## 获取重音短语

可以获取文本的重音短语信息以便查看与编辑：

```php theme={null}
$accentPhrasesJson = $synthesizer->createAccentPhrases($text, $styleId);
$accentPhrases = json_decode($accentPhrasesJson, true);

// 使用其他风格覆盖 mora 的音高与音素时长
$updatedJson = $synthesizer->replaceMoraData($accentPhrasesJson, $styleId);
```

## 使用 GPU 模式

在可以使用 GPU 的环境中指定 `AccelerationMode::Gpu` 可以加速：

```php theme={null}
use Revolution\Voicevox\Core\Enums\AccelerationMode;

$synthesizer = new Synthesizer($onnxruntime, $openJtalk, AccelerationMode::Gpu);

// 检查是否在 GPU 模式下
if ($synthesizer->isGpuMode()) {
    echo '当前在 GPU 模式下运行' . PHP_EOL;
}
```

## 使用多个语音模型

通过加载多个 `.vvm` 文件并切换 Style ID，可以在多个角色声音间切换使用：

```php theme={null}
$model0 = VoiceModelFile::open($voicevoxCoreDir . '/models/vvms/0.vvm');
$model1 = VoiceModelFile::open($voicevoxCoreDir . '/models/vvms/1.vvm');

$synthesizer->loadVoiceModel($model0);
$synthesizer->loadVoiceModel($model1);

// 查看模型中包含的说话人信息
$metas = json_decode($synthesizer->metas(), true);

// 卸载模型（不再需要时）
$synthesizer->unloadVoiceModel($model0->id());
```


## Related topics

- [VOICEVOX Core for PHP](/zh/packages/voicevox-core-php/index.md)
- [API 参考 - VOICEVOX Core for PHP](/zh/packages/voicevox-core-php/api.md)
- [PHP FFI](/zh/advanced/ffi.md)
- [VOICEVOX for Laravel](/zh/packages/laravel-voicevox/index.md)
- [安装与配置 - VOICEVOX for Laravel](/zh/packages/laravel-voicevox/installation.md)
