> ## 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는 웹 서버 환경(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
```

## 1단계로 음성 합성 (`tts` 메서드)

`createAudioQuery` + `synthesis`의 2단계를 생략하고 싶은 경우 `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](/ko/packages/voicevox-core-php/index.md)
- [API 레퍼런스 - VOICEVOX Core for PHP](/ko/packages/voicevox-core-php/api.md)
- [PHP FFI](/ko/advanced/ffi.md)
- [VOICEVOX for Laravel](/ko/packages/laravel-voicevox/index.md)
- [설치와 설정 - VOICEVOX for Laravel](/ko/packages/laravel-voicevox/installation.md)
