1.21 jigowatts

Great Scott!

VoiceText Web APIで遊んでみた

概要

PowerShellでVoiceText Web APIを使って遊んでみようと思い立ち、Visual Studio Code(以下VSCode)でスクリプトを書いてみました(・∀・)

f:id:sh_yoshida:20180414131937p:plain

環境

Windows10
PowerShell 5.1

VoiceText Web API

モヤさまのナレータでおなじみですね。
cloud.voicetext.jp

規約読んで利用登録してAPIキーを取得しましょう。
VSCodeを立ち上げスクリプトを書いて実行したら、わけわからんことしゃべってる?なんで?って颯爽と詰まる。

理由は日本語をしゃべらせようとして、ファイルのエンコードUTF-8のためスクリプトに書いた文字列が文字化けしたからですね。

f:id:sh_yoshida:20180414132046p:plain

PowerShell ISEで書いたスクリプトVSCodeで開いたらUTF-8 with BOMとなっていたので、スクリプトの中で日本語を書くときはUTF-8 with BOMにしておけば良さそう。あとShift JISでも大丈夫でした。

モジュール化してみた

エンコードUTF-8でもコマンドレットの引数で渡すんであれば行けたのでモジュール化してみました。
環境変数VoiceTextAPI_KEYという名前でAPIキーを登録しておきます。

■voiceTextModule.psm1

. $PSScriptRoot\voiceConverter.ps1

function ConvertTo-Voice {
    param(
        [Parameter(Mandatory)]
        [ValidateSet('show', 'haruka', 'hikari', 'takeru', 'santa', 'bear')]
        [string] $name,
        [Parameter(Mandatory)]
        [string] $text
        )
    begin{
    }
    process {
        $Speaker = [Speaker]::new($name, $text);
        $Speaker.Speak();
    }
    end {
    }
}

■voiceConverter.ps1
バージョン5からクラス構文も書けるようになったんすね。

Write-Host 'Loading...'

class Speaker {
    [string]$Name;
    [string]$Text;
    [string]$Uri = "https://api.voicetext.jp/v1/tts";
    
    Speaker ($name, $text) {
        $this.Name = $name;
        $this.Text = $text;
    }

    [string] GetAuthorization() {
        $t = $env:VoiceTextAPI_KEY + ":";
        return "Basic " `
            + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($t))
    }

    [void] Speak() {
        $outFile = ".\voicetext.wav"
        if (Test-Path $outFile){
            Remove-Item $outFile;
        }
    
        Invoke-RestMethod -Uri $this.Uri `
                    -Method POST `
                    -Headers @{Authorization=$this.GetAuthorization()} `
                    -Body @{text=$this.Text; speaker=$this.Name;} `
                    -OutFile $outFile;

        $player = New-Object System.Media.SoundPlayer -ArgumentList $outFile
        $player.Play()
    }
}

あとはモジュールをインポートして実行するだけ(^q^)b

PS> Import-Module .\voiceTextModule
PS> ConvertTo-Voice -name show -text 本当にありがとうございます。