ロゴ メインコンテンツへ
RSSフィード
「ソフトウェア開発」に関連する記事一覧

C# SpeechSynthesizerの発声時間を取得するサンプルコード

2021/07/29
(この記事の文字数: 324)

C# で SpeechSynthesizer を使って、音声合成を使ったソフトウェアを作っているのですが、音声合成が話す発声時間を知りたくなりました。ネットで調べてみると、一度 MemoryStream に波形を書き出して、その波形から尺を調べる方法が見つかりました。

https://stackoverflow.com/questions/35300158/length-in-time-of-a-wave-file

以下のようなテストコードを書いてみたところ、うまく音声合成の発声時間を取得する事ができました。

[TestMethod]
public void DurationCalcTest()
{
    var synth = new System.Speech.Synthesis.SpeechSynthesizer();
    var message = "こんにちは、これは音声合成の発生時間を取得するサンプルです。";

    {
        synth.Rate = 0;
        var sec = CalculateDuration(synth, message).TotalSeconds;
        System.Console.WriteLine($"{sec}秒");
    }

    {
        synth.Rate = 10;
        var sec = CalculateDuration(synth, message).TotalSeconds;
        System.Console.WriteLine($"{sec}秒");
    }

    {
        synth.Rate = -10;
        var sec = CalculateDuration(synth, message).TotalSeconds;
        System.Console.WriteLine($"{sec}秒");
    }
}

public System.TimeSpan CalculateDuration(System.Speech.Synthesis.SpeechSynthesizer synth, string message)
{
    using (var stream = new System.IO.MemoryStream())
    {
        synth.SetOutputToWaveStream(stream);

        synth.Speak(message);
        stream.Seek(0, System.IO.SeekOrigin.Begin);
        using (var wfr = new NAudio.Wave.WaveFileReader(stream))
        {
            return wfr.TotalTime;
        }
    }
}

テストの標準出力

5.692653秒
1.9112018秒
17.1270748秒

これでテキストを入力するだけで、そのテキストを話すのにかかる時間がおおよそ分かるので、プレゼンなどの原稿を作る時に役に立ちそうです。


  このエントリーをはてなブックマークに追加  

<<「ソフトウェア開発」の記事一覧に戻る

<<「ソフトウェア開発」の次の記事
「ソフトウェア開発」の前の記事 >>

コメント(0 件)



コンテンツロード: 0.0081 sec
Copyright(C)2006-2024 puarts All Rights Reserved