PowerShellにしゃべらせる!

、、、これも、docomo api

PS > Start-Speaking こんにちは

ってなことができます、、、って、まあ実行しないと音は出ませんけど。



スクリプト、、、の前に

これも、前回のと同様にdocomo Developer supportに登録しないと使えません。
PowerShellと会話する - じゅんじゅんのきまぐれ
を参考にちゃちゃっと登録しちゃってください。

スクリプト

System.Web.HttpUtilityを使っているので、System.Webをロードします。

function Start-Speaking() {
        [CmdletBinding()]
        Param (
                [ValidateLength(1,200)]
                [string] $Message,
                [ValidateSet('show','haruka','hikari','takeru','santa','bear')]
                [string] $Speaker = 'show',
                [ValidateSet('happiness','anger','sadness')]
                [string] $Emotion = '',
                [ValidateRange(1,2)]
                [int]    $EmotionLevel = 1,
                [ValidateRange(50,200)]
                [int]    $Pitch = 100,
                [ValidateRange(50,400)]
                [int]    $Speed = 100,
                [ValidateRange(50,200)]
                [int]    $Volume = 100,
                [ValidateSet('wav','ogg')]
                [string] $Format = 'wav'
        )

        if(!('System.Web.HttpUtility' -as [type])) {
                Add-Type -AssemblyName System.Web
        }
        $da = @{}
        $da.key = '音声合成のAPIKEYね'
        $da.s = @{}
        $da.s.text = $Message
        $da.s.speaker = $Speaker
        if($Speaker -eq 'show' -or [string]::IsNullOrEmpty($Emotion)) {
                $da.s.Remove('emotion')
                $da.s.Remove('emotion_level')
        } else {
                $da.s.emotion = $Emotion
                $da.s.emotion_level = $EmotionLevel
        }
        $da.s.pitch = $Pitch
        $da.s.speed = $Speed
        $da.s.volume = $Volume
        $da.s.format = $Format
        $postData = @()
        foreach($p in $da.s.Keys) {
                $postData += ('{0}={1}' -f $p, [System.Web.HttpUtility]::UrlEncode($da.s[$p]))
        }
        $postData = [System.Text.Encoding]::UTF8.GetBytes(($postData -join '&'))
        $webreq = [System.Net.WebRequest]::Create(('https://api.apigw.smt.docomo.ne.jp/voiceText/v1/textToSpeech?APIKEY={0}' -f $da.key))
        $webreq.Method = 'POST'
        $webreq.ContentType = 'application/x-www-form-urlencoded'
        $webreq.ContentLength = $postData.Length
        $sr = $webreq.GetRequestStream()
        $sr.Write($postData, 0, $postData.Length)
        $sr.Close()
        $webres = $webreq.GetResponse()

        $player = New-Object System.Media.SoundPlayer
        $player.Stream = $webres.GetResponseStream()
        $player.PlaySync()
        $player.Dispose()
        $webres.Close()
}

解説

音声合成 【Powerd by HOYAサービス】です。
男声や女声、キャラクター、それに速度や高低・ボリュームがいろいろ選べるようです。
初期の男声「show」以外は、感情の指定もできたりするようです。
詳細は、API説明を見てください。


応答をSystem.Media.SoundPlayerでストリーム再生するだけです。
(エラーは知らん)


PowerShell3.0以降的に正しくは、Invoke-RestMethodとかするべきなんでしょうけど、.netアプリケーションを視野に入れて、.net利用のままとしてます。