Skip to content

Instantly share code, notes, and snippets.

@takoyakiroom
Created November 25, 2022 12:48
Show Gist options
  • Save takoyakiroom/8b572a857b7366f6e1613a1b03b5970a to your computer and use it in GitHub Desktop.
Save takoyakiroom/8b572a857b7366f6e1613a1b03b5970a to your computer and use it in GitHub Desktop.
クリップボードを監視してVOICEVOXでテキスト読み上げ
using System.Media;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
namespace VOICEVOX_test
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
private extern static void AddClipboardFormatListener(IntPtr hwnd);
[DllImport("user32.dll")]
private extern static void RemoveClipboardFormatListener(IntPtr hwnd);
// クリップボード更新
private const int WM_CLIPBOARDUPDATE = 0x31D;
public Form1()
{
InitializeComponent();
// クリップボードのリスナーとして登録
AddClipboardFormatListener(Handle);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
// クリップボードリスナー解除
RemoveClipboardFormatListener(Handle);
}
private async Task<string> PostAudioQuery()
{
// URL用に変換
string talk = HttpUtility.UrlEncode(textBox1.Text);
// URL
string url = "http://localhost:50021/audio_query?text=" + talk + "&speaker=1";
// 送信内容を設定
var content = new StringContent("", Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
// 要求送る
HttpResponseMessage response = await client.PostAsync(url, content);
// 応答受ける
string resp = await response.Content.ReadAsStringAsync();
return resp;
}
}
private async Task<byte[]> PostSynthesis()
{
// URL
string url = "http://localhost:50021/synthesis?speaker=1";
// 送信内容を設定
var content = new StringContent(textBox2.Text, Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
// 要求送る
HttpResponseMessage response = await client.PostAsync(url, content);
// 応答受ける
byte[] resp = await response.Content.ReadAsByteArrayAsync();
return resp;
}
}
private async void button1_Click(object sender, EventArgs e)
{
// VOICEVOXにaudio_query送信
string json = await PostAudioQuery();
textBox2.Text = json;
}
private async void button2_Click(object sender, EventArgs e)
{
// VOICEVOXにsynthesis送信
byte[] bytes = await PostSynthesis();
MemoryStream wav = new MemoryStream(bytes);
SoundPlayer player = new SoundPlayer(wav);
player.Play();
}
protected override void WndProc(ref Message msg)
{
switch (msg.Msg)
{
case WM_CLIPBOARDUPDATE:
OnClipboardUpdate();
break;
}
base.WndProc(ref msg);
}
protected async void OnClipboardUpdate()
{
IDataObject clip = Clipboard.GetDataObject();
// クリップボードに入ったのはテキストか?
if (clip.GetDataPresent(DataFormats.Text))
{
// クリップボードから取得
textBox1.Text = (string)clip.GetData(DataFormats.Text);
// VOICEVOXへ
textBox2.Text = await PostAudioQuery();
byte[] wave = await PostSynthesis();
// 再生
MemoryStream memStream = new MemoryStream(wave);
SoundPlayer player = new SoundPlayer(memStream);
player.Play();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment