4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

VOICEVOXをC#でREST-API経由で喋らせる(その1 発話)

Last updated at Posted at 2023-02-26

概要

VOICEVOXをC#で使う記事が少ないため作成

  • 以下の点は参考サイトから導入してください
    • VOICEVOXのインストール
    • VOICEVOXの起動
    • コンソールプロジェクトの作成

環境

VOICEVOX Ver. 0.14.1
Visual Studio 2022
.net7.0
コンソール アプリ

流れ

  • 音声クエリを生成
  • 音声合成
  • 音声を保存
  • 音声再生する
    NuGetからSystem.Windows.Extensionを追加する

参考文献

プログラム

console.cs
using System.Media;
using System.Net.Http.Headers;

using (var httpClient = new HttpClient())
{
    string query;
    int speaker = 1;
    string text = "あかさたな";

    // 音声クエリを生成
    using (var request = new HttpRequestMessage(new HttpMethod("POST"), $"http://localhost:50021/audio_query?text={text}&speaker={speaker}"))
    {
        request.Headers.TryAddWithoutValidation("accept", "application/json");

        request.Content = new StringContent("");
        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");

        var response = await httpClient.SendAsync(request);

        query = response.Content.ReadAsStringAsync().Result;
        Console.WriteLine(query);
    }

    // 音声クエリから音声合成
    using (var request = new HttpRequestMessage(new HttpMethod("POST"), "http://localhost:50021/synthesis?speaker=1&enable_interrogative_upspeak=true"))
    {
        request.Headers.TryAddWithoutValidation("accept", "audio/wav");

        request.Content = new StringContent(query);
        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

        var response = await httpClient.SendAsync(request);

        // 音声を保存
        using (var fileStream = System.IO.File.Create("test.wav"))
        {
            using (var httpStream = await response.Content.ReadAsStreamAsync())
            {
                httpStream.CopyTo(fileStream);
                fileStream.Flush();
            }
        }
    }
}

//読み込む
var player = new SoundPlayer("test.wav");
//再生する
player.PlaySync();
Console.WriteLine("再生完了");

そのまま再生

using (var httpStream = await response.Content.ReadAsStreamAsync())
{
    //読み込む
    var player = new SoundPlayer(httpStream);
    //再生する
    player.Play();
}

備考

時間計測

Ryzen 7 3700X
”あかさたな”
(初起動時)音声クエリ生成...2秒程度
(2回目)音声クエリ生成...0.05秒程度
音声クエリから音声合成..0.4秒程度

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?