据我所知,Google Cloud 已正确配置。我已经尝试了 API 密钥和服务帐户密钥,但在使用 curl 连接时不断收到 401 Unauthorized。结果 401 未经授权。我没有使用 Google 库,因为我无法为我要构建的这个小应用程序访问它。
public async Task GenerateResponse(Input input, Voice voice, AudioConfig audioConfig, string outputFile)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "MyAPIKey");
var request = new { input = input, voice=voice, audioConfig=audioConfig };
var jsonRequest = JsonConvert.SerializeObject(request);
var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
using (var response = await client.PostAsync("https://texttospeech.googleapis.com/v1/text:synthesize", content))
{
response.EnsureSuccessStatusCode();
using (var audioStream = await response.Content.ReadAsStreamAsync())
{
using (var outputStream = File.Create(outputFile))
{
await audioStream.CopyToAsync(outputStream);
}
}
}
}
}