在 C# 中使用 Youtube API V3 从频道获取视频
Get Videos from a Channel using Youtube API V3 in C#
我有一个 ASP.Net 网页,我在其中使用 V2 显示我频道中的 Youtube 视频。由于 Google 已停用 V2 API,我正在尝试使用 V3 API,但无法从频道获取视频。
我确实看过 github 上的示例,但该示例显示了如何创建视频,但无法检索视频。在 SO 上搜索,我看到使用 php 库的示例,我正在寻找特定于 C# 的内容。
谁能帮我解决这个问题?
通过将频道 ID 添加到 Search.list 它 returns 频道中的视频列表。
var searchListRequest = service.Search.List("snippet");
searchListRequest.ChannelId = "UCIiJ33El2EakaXBzvelc2bQ";
var searchListResult = searchListRequest.Execute();
更新对正在发生的事情的评论解释的回复:
实际搜索 returns 与频道 ID 相关的所有内容,毕竟您是在搜索频道 ID。
搜索 returns 包含多个项目的 SearchListResponse。每个项目都是类型 SearchResource 搜索资源可以有不同的类型或种类。在下面的两张图片中,您可以看到第一张是 kind youtube#channel
,第二张是 kind youtube#video
,您可以循环浏览它们并找到 youtube 视频。如果您滚动到 search.list 页面的底部,您可以尝试查看 API 返回的原始 JSon。
解决方法:
现在,如果您只想取回视频,只需在请求中添加类型即可告诉它您想要的只是视频:
searchListRequest.Type = "video";
虽然前一段时间被问到,但我也一直在搜索如何使用 C# 从频道获取视频(全部)。目前我有支持分页的方法(可能可以做得更好:))
希望对您有所帮助
public Task<List<SearchResult>> GetVideosFromChannelAsync(string ytChannelId)
{
return Task.Run(() =>
{
List<SearchResult> res = new List<SearchResult>();
var _youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "AIzaXyBa0HT1K81LpprSpWvxa70thZ6Bx4KD666",
ApplicationName = "Videopedia"//this.GetType().ToString()
});
string nextpagetoken = " ";
while (nextpagetoken != null)
{
var searchListRequest = _youtubeService.Search.List("snippet");
searchListRequest.MaxResults = 50;
searchListRequest.ChannelId = ytChannelId;
searchListRequest.PageToken = nextpagetoken;
// Call the search.list method to retrieve results matching the specified query term.
var searchListResponse = searchListRequest.Execute();
// Process the video responses
res.AddRange(searchListResponse.Items);
nextpagetoken = searchListResponse.NextPageToken;
}
return res;
});
}
在一个 youtube 频道中,有很多播放列表。每个播放列表下都有很多视频。所以一开始,我拿出播放列表,然后从每个播放列表中拿出视频列表。所以这是我在我的项目中实施的解决方案。这是一个完整的代码,用于从 youtube 频道获取视频并像 youtube 频道一样显示视频,其中包含视频发布的天数等信息。在这里我还实现了缓存以更快地加载视频。我花了很多时间来实现这个。希望对你有帮助。
型号:
public class VideoViewModel
{
public List<PlayList> PlayList { get; internal set; }
}
public class PlayList
{
public string Title { get; set; }
public string Description { get; set; }
public string Id { get; set; }
public string Url { get; set; }
public List<VideoList> VideoList { get; set; }
}
public class VideoList
{
public string Title { get; set; }
public string Description { get; set; }
public string Id { get; set; }
public string Url { get; set; }
public string PublishedDate { get; set; }
}
控制器:
public ActionResult Index(string VideoId, string VideoType, int? PageNo)
{
VideoViewModel ob = new VideoViewModel();
ob = GetFromList();
return View(ob);
}
VideoViewModel GetFromList()
{
VideoViewModel ob = new VideoViewModel();
IDatabase cache = Connection.GetDatabase();
string serializedVideos = cache.StringGet("");
if (!String.IsNullOrEmpty(serializedVideos))
{
ob.PlayList = JsonConvert.DeserializeObject<List<PlayList>>(serializedVideos);
}
else
{
GetYoutubeVideosFromApi(ob);
cache.StringSet("", JsonConvert.SerializeObject(ob.PlayList));
}
return ob;
}
public void GetYoutubeVideosFromApi(VideoViewModel ob)
{
ob.PlayList = new List<PlayList>();
WebClient wc = new WebClient { Encoding = Encoding.UTF8 };
try
{
string jsonstring = wc.DownloadString("https://www.googleapis.com/youtube/v3/playlists?part=snippet&key=yourkey&maxResults=50&channelId=yourchaneelid");
JObject jobj = (JObject)JsonConvert.DeserializeObject(jsonstring);
foreach (var entry in jobj["items"])
{
PlayList pl = new PlayList();
pl.Title = entry["snippet"]["title"].ToString();
pl.Description = entry["snippet"]["description"].ToString();
pl.Id = entry["id"].ToString();
pl.VideoList = new List<VideoList>();
string jsonstring2 = wc.DownloadString("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=" + entry["id"].ToString() + "&key=yourkey&maxResults=50");
JObject jobj2 = (JObject)JsonConvert.DeserializeObject(jsonstring2);
foreach (var vl in jobj2["items"])
{
VideoList v = new VideoList();
v.Title = vl["snippet"]["title"].ToString();
v.Description = vl["snippet"]["description"].ToString();
v.Id = vl["snippet"]["resourceId"]["videoId"].ToString();
v.Url = vl["snippet"]["thumbnails"]["medium"]["url"].ToString();
var publishTime = vl["snippet"]["publishedAt"].ToString();
var temp = DateTime.Parse(publishTime);
v.PublishedDate = GetTimeInMonth(temp);
pl.VideoList.Add(v);
}
ob.PlayList.Add(pl);
}
}
catch (Exception ex)
{
throw;
}
}
public static string GetTimeInMonth(DateTime objDateTime)
{
const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;
var ts = new TimeSpan(DateTime.UtcNow.Ticks - objDateTime.Ticks);
double delta = Math.Abs(ts.TotalSeconds);
if (delta < 1 * MINUTE)
return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
if (delta < 2 * MINUTE)
return "a minute ago";
if (delta < 45 * MINUTE)
return ts.Minutes + " minutes ago";
if (delta < 90 * MINUTE)
return "an hour ago";
if (delta < 24 * HOUR)
return ts.Hours + " hours ago";
if (delta < 48 * HOUR)
return "yesterday";
if (delta < 30 * DAY)
return ts.Days + " days ago";
if (delta < 12 * MONTH)
{
int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
return months <= 1 ? "one month ago" : months + " months ago";
}
else
{
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "one year ago" : years + " years ago";
}
}
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
string cacheConnection = ConfigurationManager.AppSettings["CacheConnection"].ToString();
return ConnectionMultiplexer.Connect(cacheConnection);
});
public static ConnectionMultiplexer Connection
{
get
{
return lazyConnection.Value;
}
}
View:其实取决于你想如何展示视频列表。
我有一个 ASP.Net 网页,我在其中使用 V2 显示我频道中的 Youtube 视频。由于 Google 已停用 V2 API,我正在尝试使用 V3 API,但无法从频道获取视频。
我确实看过 github 上的示例,但该示例显示了如何创建视频,但无法检索视频。在 SO 上搜索,我看到使用 php 库的示例,我正在寻找特定于 C# 的内容。
谁能帮我解决这个问题?
通过将频道 ID 添加到 Search.list 它 returns 频道中的视频列表。
var searchListRequest = service.Search.List("snippet");
searchListRequest.ChannelId = "UCIiJ33El2EakaXBzvelc2bQ";
var searchListResult = searchListRequest.Execute();
更新对正在发生的事情的评论解释的回复:
实际搜索 returns 与频道 ID 相关的所有内容,毕竟您是在搜索频道 ID。
搜索 returns 包含多个项目的 SearchListResponse。每个项目都是类型 SearchResource 搜索资源可以有不同的类型或种类。在下面的两张图片中,您可以看到第一张是 kind youtube#channel
,第二张是 kind youtube#video
,您可以循环浏览它们并找到 youtube 视频。如果您滚动到 search.list 页面的底部,您可以尝试查看 API 返回的原始 JSon。
解决方法:
现在,如果您只想取回视频,只需在请求中添加类型即可告诉它您想要的只是视频:
searchListRequest.Type = "video";
虽然前一段时间被问到,但我也一直在搜索如何使用 C# 从频道获取视频(全部)。目前我有支持分页的方法(可能可以做得更好:))
希望对您有所帮助
public Task<List<SearchResult>> GetVideosFromChannelAsync(string ytChannelId)
{
return Task.Run(() =>
{
List<SearchResult> res = new List<SearchResult>();
var _youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "AIzaXyBa0HT1K81LpprSpWvxa70thZ6Bx4KD666",
ApplicationName = "Videopedia"//this.GetType().ToString()
});
string nextpagetoken = " ";
while (nextpagetoken != null)
{
var searchListRequest = _youtubeService.Search.List("snippet");
searchListRequest.MaxResults = 50;
searchListRequest.ChannelId = ytChannelId;
searchListRequest.PageToken = nextpagetoken;
// Call the search.list method to retrieve results matching the specified query term.
var searchListResponse = searchListRequest.Execute();
// Process the video responses
res.AddRange(searchListResponse.Items);
nextpagetoken = searchListResponse.NextPageToken;
}
return res;
});
}
在一个 youtube 频道中,有很多播放列表。每个播放列表下都有很多视频。所以一开始,我拿出播放列表,然后从每个播放列表中拿出视频列表。所以这是我在我的项目中实施的解决方案。这是一个完整的代码,用于从 youtube 频道获取视频并像 youtube 频道一样显示视频,其中包含视频发布的天数等信息。在这里我还实现了缓存以更快地加载视频。我花了很多时间来实现这个。希望对你有帮助。
型号:
public class VideoViewModel
{
public List<PlayList> PlayList { get; internal set; }
}
public class PlayList
{
public string Title { get; set; }
public string Description { get; set; }
public string Id { get; set; }
public string Url { get; set; }
public List<VideoList> VideoList { get; set; }
}
public class VideoList
{
public string Title { get; set; }
public string Description { get; set; }
public string Id { get; set; }
public string Url { get; set; }
public string PublishedDate { get; set; }
}
控制器:
public ActionResult Index(string VideoId, string VideoType, int? PageNo)
{
VideoViewModel ob = new VideoViewModel();
ob = GetFromList();
return View(ob);
}
VideoViewModel GetFromList()
{
VideoViewModel ob = new VideoViewModel();
IDatabase cache = Connection.GetDatabase();
string serializedVideos = cache.StringGet("");
if (!String.IsNullOrEmpty(serializedVideos))
{
ob.PlayList = JsonConvert.DeserializeObject<List<PlayList>>(serializedVideos);
}
else
{
GetYoutubeVideosFromApi(ob);
cache.StringSet("", JsonConvert.SerializeObject(ob.PlayList));
}
return ob;
}
public void GetYoutubeVideosFromApi(VideoViewModel ob)
{
ob.PlayList = new List<PlayList>();
WebClient wc = new WebClient { Encoding = Encoding.UTF8 };
try
{
string jsonstring = wc.DownloadString("https://www.googleapis.com/youtube/v3/playlists?part=snippet&key=yourkey&maxResults=50&channelId=yourchaneelid");
JObject jobj = (JObject)JsonConvert.DeserializeObject(jsonstring);
foreach (var entry in jobj["items"])
{
PlayList pl = new PlayList();
pl.Title = entry["snippet"]["title"].ToString();
pl.Description = entry["snippet"]["description"].ToString();
pl.Id = entry["id"].ToString();
pl.VideoList = new List<VideoList>();
string jsonstring2 = wc.DownloadString("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=" + entry["id"].ToString() + "&key=yourkey&maxResults=50");
JObject jobj2 = (JObject)JsonConvert.DeserializeObject(jsonstring2);
foreach (var vl in jobj2["items"])
{
VideoList v = new VideoList();
v.Title = vl["snippet"]["title"].ToString();
v.Description = vl["snippet"]["description"].ToString();
v.Id = vl["snippet"]["resourceId"]["videoId"].ToString();
v.Url = vl["snippet"]["thumbnails"]["medium"]["url"].ToString();
var publishTime = vl["snippet"]["publishedAt"].ToString();
var temp = DateTime.Parse(publishTime);
v.PublishedDate = GetTimeInMonth(temp);
pl.VideoList.Add(v);
}
ob.PlayList.Add(pl);
}
}
catch (Exception ex)
{
throw;
}
}
public static string GetTimeInMonth(DateTime objDateTime)
{
const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;
var ts = new TimeSpan(DateTime.UtcNow.Ticks - objDateTime.Ticks);
double delta = Math.Abs(ts.TotalSeconds);
if (delta < 1 * MINUTE)
return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
if (delta < 2 * MINUTE)
return "a minute ago";
if (delta < 45 * MINUTE)
return ts.Minutes + " minutes ago";
if (delta < 90 * MINUTE)
return "an hour ago";
if (delta < 24 * HOUR)
return ts.Hours + " hours ago";
if (delta < 48 * HOUR)
return "yesterday";
if (delta < 30 * DAY)
return ts.Days + " days ago";
if (delta < 12 * MONTH)
{
int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
return months <= 1 ? "one month ago" : months + " months ago";
}
else
{
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "one year ago" : years + " years ago";
}
}
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
string cacheConnection = ConfigurationManager.AppSettings["CacheConnection"].ToString();
return ConnectionMultiplexer.Connect(cacheConnection);
});
public static ConnectionMultiplexer Connection
{
get
{
return lazyConnection.Value;
}
}
View:其实取决于你想如何展示视频列表。