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

# Specifica del file .vvproj - VOICEVOX for Laravel

> Specifica pratica per caricare il JSON .vvproj dell'editor VOICEVOX e generare talk e song in Laravel.

## Obiettivo

Sfruttare direttamente i file `.vvproj` dell'editor VOICEVOX per rigenerare talk e song in Laravel.

## Struttura di primo livello

`.vvproj` è JSON in UTF-8. Talk e song sono salvati nello stesso file.

```json theme={null}
{
  "appVersion": "0.25.2",
  "talk": {
    "audioKeys": [],
    "audioItems": {}
  },
  "song": {
    "tpqn": 480,
    "tempos": [],
    "timeSignatures": [],
    "tracks": {},
    "trackOrder": []
  }
}
```

| Chiave       | Contenuto                                         |
| ------------ | ------------------------------------------------- |
| `appVersion` | Versione dell'editor al momento del salvataggio   |
| `talk`       | Dati per il talk (`audioKeys` + `audioItems`)     |
| `song`       | Dati per il song (tempo, tempo in chiave, tracce) |

## Sezione `talk`

`talk.audioKeys` è un array ordinato, `talk.audioItems` è un Record con l'ID come chiave.

```json theme={null}
{
  "audioKeys": ["audio-item-uuid"],
  "audioItems": {
    "audio-item-uuid": {
      "text": "ずんだもんなのだ",
      "voice": {
        "engineId": "engine-uuid",
        "speakerId": "speaker-uuid",
        "styleId": 3
      },
      "query": {
        "accentPhrases": [],
        "speedScale": 1,
        "pitchScale": 0
      },
      "presetKey": "preset-uuid"
    }
  }
}
```

### TalkAudioItem

| Chiave            | Contenuto                                                                                                        |
| ----------------- | ---------------------------------------------------------------------------------------------------------------- |
| `text`            | Testo di input                                                                                                   |
| `voice.engineId`  | ID engine (corrisponde a `/engine_manifest`)                                                                     |
| `voice.speakerId` | UUID del parlante                                                                                                |
| `voice.styleId`   | ID stile. Da passare così com'è a `/synthesis?speaker={styleId}`                                                 |
| `query`           | Equivalente ad `AudioQuery`                                                                                      |
| `presetKey`       | ID preset dell'editor. Per i preset lato Laravel consulta [Preset](/it/packages/laravel-voicevox/native-presets) |

Se `.vvproj` contiene già `query`, puoi passare direttamente alla sintesi senza rieseguire `/audio_query`.

### `accentPhrases`

| Chiave            | Contenuto                                                                           |
| ----------------- | ----------------------------------------------------------------------------------- |
| `moras`           | Array di mora (le `consonant` possono essere omesse)                                |
| `accent`          | Posizione dell'accento (partendo da 1)                                              |
| `pauseMora`       | Può comparire quando si inseriscono silenzi in corrispondenza di punteggiatura ecc. |
| `isInterrogative` | Flag di interrogativa                                                               |

## Sezione `song`

```json theme={null}
{
  "tpqn": 480,
  "tempos": [{ "position": 0, "bpm": 120 }],
  "timeSignatures": [{ "measureNumber": 1, "beats": 4, "beatType": 4 }],
  "tracks": {
    "track-uuid": {
      "name": "無名トラック",
      "singer": { "engineId": "engine-uuid", "styleId": 3003 },
      "notes": []
    }
  },
  "trackOrder": ["track-uuid"]
}
```

| Chiave           | Contenuto                                                                                      |
| ---------------- | ---------------------------------------------------------------------------------------------- |
| `tpqn`           | Ticks Per Quarter Note. Il valore standard è 480                                               |
| `tempos`         | Mappa dei tempi (`position` in tick)                                                           |
| `timeSignatures` | Mappa dei tempi in chiave (`measureNumber` parte da 1)                                         |
| `tracks`         | Record con l'ID della traccia come chiave                                                      |
| `trackOrder`     | Ordine di visualizzazione/riproduzione. Deve coincidere con l'insieme delle chiavi di `tracks` |

### Track

| Chiave                             | Contenuto                                                    |
| ---------------------------------- | ------------------------------------------------------------ |
| `singer.styleId`                   | ID da passare infine a `/frame_synthesis?speaker={styleId}`  |
| `notes`                            | Array di note                                                |
| `keyRangeAdjustment`               | Aggiustamento della tonalità in semitoni                     |
| `volumeRangeAdjustment`            | Aggiustamento del volume                                     |
| `pitchEditData` / `volumeEditData` | Dati di modifica a livello di frame                          |
| `phonemeTimingEditData`            | Modifiche di timing dei fonemi per ciascun Note ID           |
| `solo` / `mute`                    | Utilizzati per determinare le tracce oggetto di riproduzione |

### Note

| Chiave       | Contenuto                 |
| ------------ | ------------------------- |
| `id`         | ID della nota (univoco)   |
| `position`   | Tick di inizio nota       |
| `duration`   | Durata della nota in tick |
| `noteNumber` | Numero di nota MIDI       |
| `lyric`      | Testo                     |

## Conversione tra tick, secondi e frame

Con tempo unico si converte così:

```text theme={null}
seconds = ticks / tpqn * 60 / bpm
frames = round(seconds * frameRate)
```

Con cambi di tempo, somma i segmenti scorrendo `tempos` in ordine crescente di `position`.

```php theme={null}
function ticksToSeconds(int $targetTick, int $tpqn, array $tempos): float
{
    $seconds = 0.0;
    $currentTick = 0;

    foreach ($tempos as $index => $tempo) {
        $nextTick = $tempos[$index + 1]['position'] ?? $targetTick;
        $segmentEnd = min($targetTick, $nextTick);

        if ($segmentEnd <= $currentTick) {
            break;
        }

        $bpm = $tempo['bpm'];
        $seconds += (($segmentEnd - $currentTick) / $tpqn) * (60 / $bpm);
        $currentTick = $segmentEnd;
    }

    return $seconds;
}
```

Per l'implementazione della conversione da tick a lunghezza di frame con l'helper `Note::len()`, consulta [Dettagli di Score e Note](/it/packages/laravel-voicevox/song-score-note).

## Flusso di generazione audio per il song

```mermaid theme={null}
flowchart TD
  A["1. Estrai le tracks nell'ordine di trackOrder"] --> B["2. Determina i target con solo/mute"]
  B --> C["3. Ordina le notes per position crescente"]
  C --> D["4. Aggiungi pause all'inizio e alla fine e crea uno Score"]
  D --> E["5. Da tick a secondi a frame per costruire frame_length"]
  E --> F["6. sing_frame_audio_query → sing_frame_f0 → sing_frame_volume"]
  F --> G["7. Genera il WAV con frame_synthesis"]
```

## Attenzioni nella modifica diretta

* L'insieme delle chiavi di `tracks` deve sempre coincidere con `trackOrder`
* Analogamente sincronizza `talk.audioKeys` e `talk.audioItems`
* Mantieni `position >= 0`, `duration >= 1` e `noteNumber` in `0..127`
* Di solito `tempos[0].position` è `0` e `timeSignatures[0].measureNumber` è `1`
* Se possibile, conserva le chiavi sconosciute nel risalvataggio per non rompere la compatibilità con versioni future

## Esempio in codice Laravel

Esempio minimo per caricare un `.vvproj` e generare talk e song.

```php theme={null}
use Illuminate\Support\Facades\Storage;
use Revolution\Voicevox\Client\TalkAudioQuery;
use Revolution\Voicevox\Song\Note;
use Revolution\Voicevox\Song\Score;
use Revolution\Voicevox\Voicevox;

$project = json_decode(
    Storage::disk('local')->get('voicevox/sample.vvproj'),
    true,
    flags: JSON_THROW_ON_ERROR,
);

// Talk: sintetizza usando direttamente la query salvata
foreach ($project['talk']['audioKeys'] as $audioKey) {
    $item = $project['talk']['audioItems'][$audioKey];

    Voicevox::talk($item['text'], id: $item['voice']['styleId'])
        ->tap(fn (TalkAudioQuery $talk) => $talk->audioQuery = array_replace($talk->audioQuery, $item['query']))
        ->generate(id: $item['voice']['styleId'])
        ->storeAs('vvproj/talk', "{$audioKey}.wav");
}

// Song: qui convertiamo la duration della prima traccia in frame_length e generiamo
$trackId = $project['song']['trackOrder'][0];
$track = $project['song']['tracks'][$trackId];
$bpm = $project['song']['tempos'][0]['bpm'] ?? 120;

$score = Score::make([
    Note::make(length: 15, lyric: '', key: null),
    ...collect($track['notes'])->map(
        fn (array $note) => Note::make(
            length: Note::len(ticks: $note['duration'], bpm: $bpm),
            lyric: $note['lyric'] ?? 'ら',
            key: $note['noteNumber'],
            id: $note['id'] ?? null,
        ),
    )->all(),
    Note::make(length: 2, lyric: '', key: null),
]);

Voicevox::song($score, teacher: 6000)
    ->generate(id: $track['singer']['styleId'])
    ->storeAs('vvproj/song', "{$trackId}.wav");
```


## Related topics

- [Guida allo sviluppo di app con l'API del motore - VOICEVOX for Laravel](/it/packages/laravel-voicevox/app-guide.md)
- [VOICEVOX Core for PHP](/it/packages/voicevox-core-php/index.md)
- [Modalità nativa - Dizionario utente - VOICEVOX for Laravel](/it/packages/laravel-voicevox/native-user-dict.md)
- [Modalità client: Talk (sintesi vocale da testo) - VOICEVOX for Laravel](/it/packages/laravel-voicevox/client-talk.md)
- [Integrazione con Laravel AI SDK - VOICEVOX for Laravel](/it/packages/laravel-voicevox/ai-sdk.md)
