hung pro vn

[C#] Tutorial Auto Upload Video Youtube using Youtube APi v3 csharp

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:

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:

Hướng dẫn bình luận

Mọi người để lại bình luận góp ý, nhận xét về những bài viết mà mình chia sẽ văn minh lịch sự hay kích động, Không spam, không chèn link quảng cáo, bán hàng, Không sử dụng từ ngữ thô tục, xúc phạm, kích động, Link chỉ được phép khi thực sự liên quan đến nội dung bài viết, Không mạo danh người khác hoặc sử dụng email giả, Bình luận vi phạm sẽ bị xóa không cần thông báo trước.
Mọi người lưu ý răng, nếu muốn chia sẽ code ở bình luần thì cần mã hóa code trước khi bỏ vào khung nhé. :)
⑴ Chèn ℂ𝕤𝕤 theo mẫu : [pre css] CSS [/pre]
⑵ Chèn ℍ𝕥𝕞𝕝 theo mẫu : [pre html] HTML [/pre]
⑶ Chèn 𝕁𝕒𝕧𝕒𝕤𝕔𝕣𝕚𝕡𝕥 theo mẫu : [pre js] Javascript [/pre]

🖼️ Chèn 𝕀𝕞𝕒𝕘𝕖 theo mẫu : [img] Link hình ảnh [/img]
🎞️ Chèn Video 𝕐𝕠𝕦𝕥𝕦𝕓𝕖 theo mẫu : [youtube] Link Youtube [/youtube]

6 Nhận xét

  1. không có mục tải full source code hả e? hay demo chương trình ấy?

    Trả lờiXóa
    Trả lời
    1. link download bị lỗi c ạ, còn demo e chưa test nên chưa có

      Xóa
  2. chất lượng đó e, có demo k? send a test thử xem nào?

    Trả lờiXóa
  3. https://www.thegioididong.com/game-app/top-10-phan-mem-lap-trinh-c-c-cho-may-tinh-windows-macos-1317109

    Trả lờiXóa
  4. good men <3, nếu tích hợp được sub kênh với like video nữa thì ok hơn đó bạn :D

    Trả lờiXóa

Top