在Google Cloud Speech API 调用注意事项及调用方式__.Net版2中描述过将上传在Google Storage中的音频文件通过调用Cloud Speech API转换为文字,里面涉及到的文件上传是在Google Cloud Platform的Storage中进行手动添加,这样很不方便。针对此问题,下面详细描述使用C#如何将文件上传到Google的Storage中。
前提条件
注册Google帐号,登录Google Cloud Platform,创建项目,在API管理器中添加项目凭据。凭据1为服务账号密匙,OAuth客户端ID。其具体操作见文档–Google Cloud Speech API 调用注意事项,里面有详细操作步骤及步骤截图。
上传文件
var clientSecrets = new ClientSecrets();
clientSecrets.ClientId = "添加OAutho其它类型客户端的Id";
clientSecrets.ClientSecret = "添加OAutho其它类型客户端的密匙";
var scopes = new[] { @"https://www.googleapis.com/auth/devstorage.full_control" };//使用Google的auth作用域
var cts = new CancellationTokenSource();
try
{
var userCredential =
await GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets, scopes, "Google云平台帐号", cts.Token);
await userCredential.RefreshTokenAsync(cts.Token);
string projectId = "选择的项目名称"; //创建项目凭据服务帐号密匙json文件中的project_id
try
{
StorageClient storageClient = StorageClient.Create();//创建Google API的存储客户端
string bucketName = "云存储中Bucket的名称";
var listBuckets = storageClient.ListBuckets(projectId).Where(b => b.Name == bucketName).ToList();
if (listBuckets.Count == 0)
{//不存在则创建Bucket
storageClient.CreateBucket(projectId, bucketName);
Console.WriteLine($"Bucket {bucketName} has created.");
}
Console.WriteLine($"Bucket Name:{bucketName}");
FileStream fileStream = null;
try
{
fileStream = new FileStream("文件本地路径", FileMode.Open);
Console.WriteLine($"{filename} is uploading. Waiting...");
await storageClient.UploadObjectAsync(bucketName, filename, "audio/wav", fileStream);
var getResult = storageClient.ListObjects(bucketName, "").Where(o => o.Name == filename).ToList();
if (getResult.Count == 1)
{
Console.WriteLine("上传成功!");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (fileStream != null)
{
fileStream.Close();
fileStream.Dispose();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("The program is exiting!");
Thread.Sleep(2000);
return;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}