Get Video Duration of a YouTube Video with youtube v3 API c# - c#

I tried to get the the length of a Video i searched before, with the youtube v3 API you can download at nuget.org.
I know there are a lot of solution, but they are always written in php.
That is the code I am using Right now:
var searchListRequest = youtubeService.Search.List("snippet");
earchListRequest.Q = Find;
searchListRequest.MaxResults = 5;
var searchListResponse = await searchListRequest.ExecuteAsync();
foreach (var searchResult in searchListResponse.Items)
{
switch (searchResult.Id.Kind)
{
case "youtube#video":
break;
}
}
Thanks for any kind of help :)

You can donwlaod the Json version of the video :
WebClient myDownloader = new WebClient();
myDownloader.Encoding = System.Text.Encoding.UTF8;
string jsonResponse=myDownloader.DownloadString(
"https://www.googleapis.com/youtube/v3/videos?id=" + yourvideoID+ "&key="
+ youtubekey + "&part=contentDetails");
dynamic dynamicObject = Json.Decode(jsonResponse);
string tmp = dynamicObject.items[0].contentDetails.duration;
var Duration = Convert.ToInt32
(System.Xml.XmlConvert.ToTimeSpan(tmp).TotalSeconds);

Related

youtube v3 api request timeout

I'm working on project that uses the YouTube api v3 with the Google .net client libary.
It's done, however sometimes it takes long time to respond when getting a video-list from playlist id. When this happens, it gives error "bad request" after 1 minute and tells me request timed out.
Is there any way to increase the request timeout or another solution for this problem?
List<YTVideo> videos = new List<YTVideo>();
var searchRequest = youtubeService.PlaylistItems.List("snippet");
searchRequest.PlaylistId = playlistId;
searchRequest.MaxResults = 1;
var searchResponse = await searchRequest.ExecuteAsync();
var playlistItemsInfo = searchResponse.Items.FirstOrDefault();
// to get videos from playlistItemsInfo
foreach (var searchResult in searchResponse.Items)
{
var videoSearchRequest = youtubeService.Videos.List("snippet, statistics, contentDetails");
videoSearchRequest.Id = searchResult.Snippet.ResourceId.VideoId;
videoSearchRequest.MaxResults = 1;
var videoSearchResponse = videoSearchRequest.Execute();
var video = videoSearchResponse.Items.FirstOrDefault();
if (video != null)
{
YTVideo yTVideo = new YTVideo
{
Title = video.Snippet.Title,
VideoId = video.Id,
Image = video.Snippet.Thumbnails.Maxres != null ? video.Snippet.Thumbnails.Maxres.Url : video.Snippet.Thumbnails.High.Url,
IsSelected = true
};
videos.Add(yTVideo);
}
}
My problem happens in searchResponse when I execute search the request.

Get "initial Key" value from .mp3 file

I can't find a way to read the "initial key" property from an mp3 file to use the song information in my application.
I've already tried to find libraries which do the job for me. I found TagLib# which is a very cool solution for getting tags/properties of different file formats. (including mp3).
I can use this library to get the title, the artist, the beats per minute and so on.. only the initial key value is missing for my use which isn't featured, unfortunately.
I also tried to find other solutions which support the initial key property but I haven't found one.
I already found a source which seems to address the same issue and solves it with using TagLib#, but I can't figure out how he solved that problem.
Use Ctrl + F and search for "Initial" to find the code block.
You can find the link here
I'll post a short part of my code which can be used to determine different info about one song in a pattern like this: (["bpm"]"title" - "artist")
var file = TagLib.File.Create(filePath);
return $"[{file.Tag.BeatsPerMinute}]{file.Tag.Title} - {file.Tag.FirstPerformer}";
Thanks for any help or recommendations in advance! :)
Try this:
public static void Main(string[] args)
{
var path = …
var file = TagLib.File.Create (path);
var id3tag = (TagLib.Id3v2.Tag)file.GetTag (TagTypes.Id3v2);
var key = ReadInitialKey (id3tag);
Console.WriteLine ("Key = " + key);
}
static string ReadInitialKey(TagLib.Id3v2.Tag id3tag)
{
var frame = id3tag.GetFrames<TextInformationFrame>().Where (f => f.FrameId == "TKEY").FirstOrDefault();
return frame.Text.FirstOrDefault() ;
}
On Windows 10 you can also use:
async Task<string> ReadInitialKey(string path)
{
StorageFile file = await StorageFile.GetFileFromPathAsync(path);
Windows.Storage.FileProperties.MusicProperties musicProperties = await file.Properties.GetMusicPropertiesAsync();
var props = await musicProperties.RetrievePropertiesAsync(null);
var inkp = props["System.Music.InitialKey"];
return (string)inkp;
}
See here for documentation on MusicProperties object and here for the valid music properties.
You can use the Shell to read all MP3 properties.
Test on Windows 10, VS 2015 =>
// Add Reference Shell32.DLL
string sFolder = "e:\\";
string sFile= "01. IMANY - Don't Be so Shy (Filatov & Karas Remix).mp3";
List<string> arrProperties = new List<string>();
Shell objShell = new Shell();
Folder objFolder;
objFolder = objShell.NameSpace(sFolder);
int nMaxProperties = 332;
for (int i = 0; i < nMaxProperties; i++)
{
string sHeader = objFolder.GetDetailsOf(null, i);
arrProperties.Add(sHeader);
}
FolderItem objFolderItem = objFolder.ParseName(sFile);
if (objFolderItem != null)
{
for (int i = 0; i < arrProperties.Count; i++)
{
Console.WriteLine((i + ('\t' + (arrProperties[i] + (": " + objFolder.GetDetailsOf(objFolderItem, i))))));
}
}
Just borrowing code from nuget: mono TaglibSharp:
var tfile = TagLib.File.Create(#"..");
string initialKey = null;
if (tfile.GetTag(TagTypes.Id3v2) is TagLib.Id3v2.Tag id3v2)
{
/*
// test: add custom Initial Key tag
var frame = TextInformationFrame.Get(id3v2, "TKEY", true);
frame.Text = new[] {"qMMM"};
frame.TextEncoding = StringType.UTF8;
tfile.Save();
*/
var frame = TextInformationFrame.Get(id3v2, "TKEY", false);
initialKey = frame?.ToString();
}

How to download a picture from the site?

I am trying to make a parser based on "AngleSharp".
I use the following code for download:
var itemsAttr = document.QuerySelectorAll("img[id='print_user_photo']");
string foto_url = itemsAttr[0].GetAttribute("src");
string path = pathFolderIMG + id_source + ".jpg";
WebClient webClient = new WebClient();
webClient.DownloadFile(foto_url, path);
For pages "type_1" -link - the code works.
For pages "type_2" - link - the code does not work.
How to download photos for pages "type_2"?
Please read the AngleSharp documentation carefully, e.g., looking at the FAQ we get:
var imageUrl = #"https://via.placeholder.com/150";
var localPath = #"g:\downloads\image.jpg";
var download = context.GetService<IDocumentLoader>().FetchAsync(new DocumentRequest(new Url(imageUrl)));
using (var response = await download.Task)
{
using (var target = File.OpenWrite(localPath))
{
await response.Content.CopyToAsync(target);
}
}
where we used a configuration like
var config = Configuration.Default.WithDefaultLoader(new LoaderOptions { IsResourceLoadingEnabled = true }).WithCookies();
var context = BrowsingContext.New(config);

Is there a way to bypass google's 100 search quota?

Google has a 100 search quota, which is way too low to be of any use. Every time I run a search, the quota increases by 1. Here's the code:
string apiKey = "(MY API KEY HERE)";
string cx = "(MY CUSTOM SEARCH ENGINE CODE HERE)";
var tempi = 0;
var svc = new Google.Apis.Customsearch.v1.CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey });
string query = "test"
potato = 0;
var listRequest = svc.Cse.List(query);
listRequest.Cx = cx;
var search = listRequest.Execute();
foreach (var result in search.Items.Take(3))
{
if (potato == 0)
{
console.WriteLine("**Title:** " + result.Title + "\n**Link:** " + result.Link);
potato += 1;
}
}
Is there any way of using this without having to use up the query every time? If not, is there any other API that can do something similar to this?
This is part of Google's commercial model. If you want to exceed the quota, then you need to start paying for the service.
You can find the pricing here.

Google YouTube API not retrieving all videos

I'm using the v3 Google YouTubeAPI to get all videos from a channel, but of the 3 available, only one is returned. Any idea what is going wrong? Here is the code for the function:
public List<Video> GetVideos()
{
var vids = new List<Video>();
YouTubeService youtube = new YouTubeService(new BaseClientService.Initializer());
SearchResource.ListRequest listRequest = youtube.Search.List("id,snippet");
listRequest.Key = WebConfigurationManager.AppSettings["youTubeKey"];
listRequest.ChannelId = WebConfigurationManager.AppSettings["youTubeChannel"];
listRequest.MaxResults = 25;
listRequest.Type = "video";
SearchListResponse resp = listRequest.Execute();
foreach (SearchResult result in resp.Items)
{
vids.Add(new Video(result.Id.VideoId, result.Snippet));
}
return vids;
}
I did verify that all 3 videos are public, and do play on YouTube.

Categories