はじめに
この記事では UnityWebRequest を使ってリモートにある MP3 ファイルを AudioClip として取得する方法を超絶ザックリと解説します。
結論
結論としては以下のようなコードになります。
(これは OpenAI の Text To Speech の API から MP3 ファイルを取得しているやつです)
public static async UniTask<AudioClip> GetVoiceClipFromTextAsync(string text)
{
Dictionary<string, string> headers = new()
{
{"Authorization", "Bearer " + "API キー"},
{"Content-type", "application/json"},
{"X-Slack-No-Retry", "1"}
};
TtsRequest request = new()
{
model = "tts-1-hd",
input = text,
voice = "nova",
response_format = "mp3",
speed = 1f
};
string jsonRequest = JsonUtility.ToJson(request);
using UnityWebRequest uwr = new("https://api.openai.com/v1/audio/speech", "POST")
{
uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(jsonRequest)),
//ここが通常と違う↓
downloadHandler = new DownloadHandlerAudioClip(string.Empty, AudioType.MPEG)
};
foreach (KeyValuePair<string, string> header in headers)
{
uwr.SetRequestHeader(header.Key, header.Value);
}
try
{
await uwr.SendWebRequest();
}
catch (Exception e)
{
throw e;
}
if (uwr.result == UnityWebRequest.Result.ConnectionError || uwr.result == UnityWebRequest.Result.ProtocolError)
{
throw new Exception();
}
//ここも通常と違う↓
return DownloadHandlerAudioClip.GetContent(uwr);
}
ポイントは以下の通りです。
- UnityWebRequest を作成するときは downloadHandler に「new DownloadHandlerAudioClip(string.Empty, AudioType.MPEG)」を設定しましょう(URL から音声ファイルを直接取得しているわけではないので DownloadHandlerAudioClip() の第一引数の文字列は何でもいいっぽいです)
- UnityWebRequest の送信後は DownloadHandlerAudioClip.GetContent() で MP3 ファイルを AudioClip として取得しましょう
- 返って来るコンテンツが MP3 ファイルの場合は DownloadHandler.GetData() などでコンテンツをバイナリデータで取得した後に AudioClip に変換するといったことは自分の調べた限りでは難しそうです