【发布时间】:2017-09-14 19:31:22
【问题描述】:
我有一个 youtube 上传器,我正在从一个音频文件生成一个视频,效果很好,但是当我上传到 Youtube 时,当我试图等待它完成上传后再重复时,程序仍然运行
我在这里生成一个视频:
private void button2_Click(object sender, EventArgs e)
{
if (status.Text == "Stopped")
{
if (!generatearticle.IsBusy)
{
// started
status.Text = "Started";
status.ForeColor = System.Drawing.Color.Green;
start.Text = "Stop Generating";
generatearticle.RunWorkerAsync();
}
}
else
{
if(generatearticle.IsBusy)
{
generatearticle.CancelAsync();
// started
status.Text = "Stopped";
status.ForeColor = System.Drawing.Color.Red;
start.Text = "Start Generating";
}
}
}
private void core()
{
// generate audio
int i = 0;
for (int n = 1; n < co; n++)
{
// generate video and upload to
// youtube, this generates, but
// when uploading to youtube this for
// loop carries on when I want it to
// upload to youtube first before carrying on
generatevideo(image, articlename);
}
}
private void generateVideo(string images, String articlename)
{
//generate the video here, once done upload
{code removed, this just generates a video, nothing important}
// now upload (but I want it to finish before repeating the core() function
try
{
new UploadVideo().Run(articlename, file);
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
ThreadSafe(() =>
{
this.Invoke((MethodInvoker)delegate
{
status.Text = e.Message;
status.ForeColor = System.Drawing.Color.Red;
});
});
}
}
}
我如何上传到 Youtube:
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
namespace articletoyoutube
{
/// <summary>
/// YouTube Data API v3 sample: upload a video.
/// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
/// See https://code.google.com/p/google-api-dotnet-client/wiki/GettingStarted
/// </summary>
class UploadVideo
{
// to access form controlls
Form1 core = new Form1();
public async Task Run(string articlename, string filelocation)
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows an application to upload files to the
// authenticated user's YouTube channel, but doesn't allow other types of access.
new[] {
YouTubeService.Scope.YoutubeUpload
},
"user",
CancellationToken.None
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = articlename;
video.Snippet.Description = "News story regarding" + articlename;
video.Snippet.Tags = new string[] {
"news",
"breaking",
"important"
};
video.Snippet.CategoryId = "25"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "public"; // or "private" or "public"
var filePath = filelocation; // Replace with path to actual movie file.
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
await videosInsertRequest.UploadAsync();
}
}
void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
{
switch (progress.Status)
{
case UploadStatus.Uploading:
core.prog_up.Text = "{0} bytes sent." + progress.BytesSent;
break;
case UploadStatus.Failed:
core.status.Text = "An error prevented the upload from completing.\n{0}" + progress.Exception;
core.status.ForeColor = System.Drawing.Color.Red;
break;
}
}
void videosInsertRequest_ResponseReceived(Video video)
{
core.prog_up.Text = "Video id '{0}' was successfully uploaded." + video.Id;
}
}
}
后台工作者只是运行core();
当它到达函数时
new UploadVideo().Run(articlename, file);
它开始上传,但又开始重复核心功能,因此在该视频上传之前生成另一个视频....如果我使用
new UploadVideo().Run(articlename, file).Wait();
然后程序只是停止并不确定地等待直到我关闭程序,我如何等待 Upload 类/方法完成,然后再继续核心方法中的 fore 循环?
对于回答的人,当我在新的上传之前添加等待时......它给了我:
严重性代码描述项目文件行抑制状态 错误 CS4033 'await' 运算符只能在异步中使用 方法。考虑用'async'修饰符标记这个方法和 将其返回类型更改为 '任务'。 articletoyoutube C:\Users\Laptop\Documents\Visual Studio 2017\Projects\articletoyoutube\articletoyoutube\Form1.cs 254 活动
【问题讨论】:
-
啊哈-老-我如何同步调用异步方法。普遍接受的答案是“不要这样做” - 谷歌“同步调用异步方法”进行长时间讨论
-
听起来你应该使用 Async/await
-
我几乎 100% 确定
UploadVideo中的Form1 core = new Form1();是一个等待发生的错误,您永远不需要调用new Form1()您应该传递一个现有实例(这与解决你的问题) -
我同意。但是我试图在使用 getter 和 setter 之前让整个脚本正常工作,所以我至少知道它正在工作:P
标签: c# youtube youtube-api