VoiceText Web APIで遊んでみた
概要
PowerShellでVoiceText Web APIを使って遊んでみようと思い立ち、Visual Studio Code(以下VSCode)でスクリプトを書いてみました(・∀・)
環境
Windows10
PowerShell 5.1
VoiceText Web API
モヤさまのナレータでおなじみですね。
cloud.voicetext.jp
規約読んで利用登録してAPIキーを取得しましょう。
VSCodeを立ち上げスクリプトを書いて実行したら、わけわからんことしゃべってる?なんで?って颯爽と詰まる。
理由は日本語をしゃべらせようとして、ファイルのエンコードがUTF-8
のためスクリプトに書いた文字列が文字化けしたからですね。
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 本当にありがとうございます。