> ## 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';

// 要合成的文字與樣式 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);

// 以其他樣式覆寫音節音高與音素長度
$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` 檔案並切換樣式 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-TW/packages/voicevox-core-php/index.md)
- [Client 模式 - 使用者字典 - VOICEVOX for Laravel](/zh-TW/packages/laravel-voicevox/client-user-dict.md)
- [官方 SDK 相容層的使用方式](/zh-TW/packages/laravel-copilot-sdk/bare-usage.md)
- [入門 - VOICEVOX for Laravel](/zh-TW/packages/laravel-voicevox/getting-started.md)
- [Native 模式:Song(歌聲語音合成)- VOICEVOX for Laravel](/zh-TW/packages/laravel-voicevox/native-song.md)
