[CSHARP] Tutorial Auto Upload Video Youtube using Youtube APi v3

Bài viết hôm nay, mình sẽ tiếp tục hướng dẫn cho các bạn viết một tools nhỏ có chức năng tự động upload video của các bạn lên Youtube sử dụng Youtube API V3 của google cung cấp.

Nếu bạn nào, thường làm việc hay upload video lên youtube, nếu các bạn upload ít video thì không sao, nếu các bạn upload nhiều video cùng một lúc thì lúc đó công việc của các bạn sẽ mất rất nhiều thời gian.

Giao diện demo ứng dụng:
[CSHARP] Tutorial Auto Upload Video Youtube using Youtube APi v3

Bài viết này, mình sẽ hướng dẫn các bạn cách upload video lên Youtube.

Đầu tiên, để sử dụng được Api Yoube v3, các bạn cần có một tài khoản gmail.
Sau đó, các bạn vào trang web
https://console.developers.google.com/apis/api?project=my-project-1480923364792&hl=EN

Để tạo một ứng dụng, như chúng ta thường làm việc với ứng dụng với facebook vậy.
Sau khi các bạn tạo thành công ứng dụng Google sẽ cung cấp cho chúng ta một: app_id, và một sercert_id. Và chúng ta sẽ sử dụng 2 khóa này để upload video lên youtube.
+ Sau khi tạo ứng dụng xong các bạn vào nuget để download và cài đặt packet Yoube.api.v3 vào project của mình.
Và dưới đây, là link code mẫu mà google có cung cấp cho chúng ta. Chúng ta chỉ cần đọc và tùy chỉnh lại thôi, các bạn có thể tham khảo ở link bên dưới:
https://developers.google.com/youtube/v3/code_samples/dotnet

Mình sẽ cung cấp source code cho các bạn bên dưới, các bạn chỉ cần tùy chỉnh lại các thông tin như:
  • Đường dẫn file
  • Tiêu đề video (title)
  • Mô tả video (description)
  • Tag Seo
  • Thumbnail Video...
Dưới đây là source code:
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;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace YoutubeUploadApi
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            lblstatus.Text = "Đang upload video";
            try
            {
                Thread thead = new Thread(() =>
                {
                    Run().Wait();
                });
                thead.IsBackground = true;
                thead.Start();
                
            }
            catch (AggregateException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private async Task Run()
        {
            UserCredential credential;
            using (var stream = new FileStream("client_id.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 = txtTieude.Text;
            video.Snippet.Description = txtMota.Text;
            string[] tagSeo = Regex.Split(txtTagSeo.Text, ",");d
            video.Snippet.Tags = tagSeo;
            video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "public"; // or "private" or "public"
            var filePath = txtPath.Text; // 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:
                   lblstatus.Text = String.Format("{0} bytes sent.", progress.BytesSent);
                    break;

                case UploadStatus.Failed:
                   lblstatus.Text = String.Format("An error prevented the upload from completing.
{0}", progress.Exception);
                    break;
            }
        }

        void videosInsertRequest_ResponseReceived(Video video)
        {
           lblstatus.Text = string.Format("Video id '{0}' was successfully uploaded.", video.Id);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
           if(open.ShowDialog() == DialogResult.OK)
            {
                txtPath.Text = open.FileName;
            }
        }
    }
}

Video demo ứng dụng upload video via Youtube Api v3:

PASSWORD UNZIP: HUNG.PRO.VN
DMCA.com Protection Status
Bản Quyền Thuộc Về Hung Program Viet Nam

Khoa Nguyen said...

mọi người tích hợp code để tích hợp đăng video tự động từ máy tính lên nữa thì ok nhé mọi người :D, một chương trình dạng như google drive ấy :D

Hung Program VN said...

hehe tks a, nhưng e k làm youtuber nên k dùng a nhé :D


MỌI NGƯỜI GÓP Ý CHO HUNG.PRO.VN NHÉ.
PASSWORD UNZIP: HUNG.PRO.VN

Copyright 2015 @ BomKhung.Com's