我有一个ASP.Net网页,我使用V2从我的频道显示Youtube视频。由于Google已停用V2 API,我正在尝试使用V3 API,但无法从频道获取视频。
我确实在github上查看了示例,但该示例显示了如何创建视频,但无法检索视频。在SO上搜索,我看到使用php库的例子,我正在寻找C#特有的东西。
有人可以帮我这个吗?
答案 0 :(得分:5)
通过将频道ID添加到Search.list,它会返回频道中的视频列表。
var searchListRequest = service.Search.List("snippet");
searchListRequest.ChannelId = "UCIiJ33El2EakaXBzvelc2bQ";
var searchListResult = searchListRequest.Execute();
更新对正在发生的事情的评论解释的回复:
实际上搜索会返回与频道ID相关联的所有内容,您毕竟正在搜索频道ID。
搜索返回包含许多项的SearchListResponse。每个项目都是SearchResource类型,搜索资源可以有不同的类型或种类。在下面的两张图片中,您可以看到第一张图片是youtube#channel
,第二图片是youtube#video
,您可以通过它们来查找YouTube视频。如果您滚动到search.list页面的底部,您可以尝试它并查看API返回的原始JSon。
<强>溶液强>
现在,如果你想做的就是收回视频,你可以通过在你的请求中添加类型来告诉它你想要的只是视频:
searchListRequest.Type = "video";
答案 1 :(得分:4)
虽然前段时间我曾经问过,我也一直在寻找一段时间如何使用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;
});
}
答案 2 :(得分:0)
在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;
}
}
查看:它实际上取决于您要如何显示视频列表。