如何使用C#通过YouTube API结束直播流?
使用C#通过YouTube API终止直播流的实现方案
现有代码问题分析
当前代码存在几个核心错误:
- 错误调用
LiveStreams.Delete接口:终止直播流不需要删除直播流资源,而是要将对应的**直播广播(Broadcast)**状态更新为completed - 参数使用错误:传入的
YTPublishSettings.PublisherId是发布者ID,而非目标直播的Broadcast ID - 存在冗余的凭证初始化逻辑:无需重复创建
UserCredential实例
正确实现步骤
- 确保授权范围包含
https://www.googleapis.com/auth/youtube(该权限足够操作直播状态) - 提前保存直播创建时生成的Broadcast ID(调用
LiveBroadcasts.Insert接口创建直播后,需保留返回对象的Id字段) - 调用
LiveBroadcasts.Update接口,将目标Broadcast的状态设置为completed
修正后的C#代码
using Google.Apis.Auth.OAuth2; using Google.Apis.Services; using Google.Apis.YouTube.v3; using Google.Apis.YouTube.v3.Data; using System.Threading; public class YouTubeLiveManager { public static YouTubeStreamDeleteStatus EndLiveStream(string targetBroadcastId) { // 定义所需授权范围 string[] scopes = { "https://www.googleapis.com/auth/youtube" }; // 初始化OAuth授权凭证 var credentials = GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = YTPublishSettings.PublisherClientId, ClientSecret = YTPublishSettings.PublisherClientSecret }, scopes, "user", CancellationToken.None).Result; // 刷新过期的访问令牌 if (credentials.Token.IsExpired(SystemClock.Default)) { credentials.RefreshTokenAsync(CancellationToken.None).Wait(); } // 创建YouTube服务实例 var youtubeService = new YouTubeService(new BaseClientService.Initializer { HttpClientInitializer = credentials, ApplicationName = "你的应用名称" }); // 构建直播状态更新对象:将状态设为已完成 var broadcastUpdate = new LiveBroadcast { Status = new LiveBroadcastStatus { LifeCycleStatus = "completed" } }; // 执行更新请求:仅更新status字段,传入目标Broadcast ID var updateRequest = youtubeService.LiveBroadcasts.Update(broadcastUpdate, "status", targetBroadcastId); var updatedBroadcast = updateRequest.Execute(); return new YouTubeStreamDeleteStatus { success = $"直播已成功终止,当前状态:{updatedBroadcast.Status.LifeCycleStatus}" }; } } // 自定义返回状态类 public class YouTubeStreamDeleteStatus { public string success { get; set; } }
关键说明
- Broadcast ID的获取:在创建直播流程中,调用
LiveBroadcasts.Insert接口会返回LiveBroadcast对象,需保存其Id字段,终止直播时传入该ID - 直播状态枚举:YouTube直播的生命周期状态包括
upcoming(未开始)、active(直播中)、completed(已结束),设置为completed即可终止直播 - 权限验证:确保OAuth授权流程中已获取
https://www.googleapis.com/auth/youtube权限,该权限覆盖直播状态修改操作
内容的提问来源于stack exchange,提问作者salman m
相关产品推荐
相关产品推荐

