public async Task <MemoryStream> GetStreamByYoutubeTrackAsync(YoutubeTrack track) { var stream = new MemoryStream(); var streamInfoSet = await _client.GetVideoMediaStreamInfosAsync(track.Id); var audioStreamInfo = streamInfoSet.Audio.WithHighestBitrate(); if (audioStreamInfo is null) { return(stream); } try { var mediaStream = await _client.GetMediaStreamAsync(audioStreamInfo); await mediaStream.CopyToAsync(stream); } catch (Exception) { Console.WriteLine($"Youtube Error... {track.Title}"); return(stream); } return(stream); }
public async Task SendYTAudio(IGuild guild, IMessageChannel channel, string url) { var client = new YoutubeClient(); string id = NormalizeId(url); var videoInfo = await client.GetVideoInfoAsync(id); var streamInfo = videoInfo.AudioStreams.OrderBy(s => s.Bitrate).Last(); string path = "C:\\Users\\Yeo\\documents\\visual studio 2017\\Projects\\Shucks\\Shucks\\Audio\\" + $"{videoInfo.Title}.{streamInfo.Container.GetFileExtension()}"; try { using (var input = await client.GetMediaStreamAsync(streamInfo)) using (var file = File.Create(path)) { await input.CopyToAsync(file); } await SendAudioAsync(guild, channel, path); } finally { File.Delete(path); } }
public async Task <Stream> GetOggAudioStream() { var info = await client.GetVideoMediaStreamInfosAsync(videoId); var audio = info.Audio.WithHighestBitrate(); var youtubeStream = await client.GetMediaStreamAsync(audio); return(await encoder.EncodeAsOggOpusAsync(youtubeStream)); }
public async Task <ActionResult> GetAsync(string id) { var client = new YoutubeClient(); //This should be initialized in YoutubeController constructor. var mediaInfoSet = await client.GetVideoMediaStreamInfosAsync(id); var mediaStreamInfo = mediaInfoSet.Audio.WithHighestBitrate(); var mimeType = $"audio/{mediaStreamInfo.Container.GetFileExtension()}"; var fileName = $"{id}.{mediaStreamInfo.Container.GetFileExtension()}"; return(File(await client.GetMediaStreamAsync(mediaStreamInfo), mimeType, fileName, true)); }
public FileDownload(YoutubeClient client, MuxedStreamInfo quality, string destination, IProgress <double> progress = null) { this.allowedToRun = true; this.youtubeClient = client; this.videoQuality = quality; this.sourceStream = client.GetMediaStreamAsync(quality).Result; this.destination = destination; this.disposeOnCompletion = true; this.chunkSize = 10000; this.contentLength = new Lazy <int>(() => Convert.ToInt32(GetContentLength())); this.progress = progress; this.BytesWritten = 0; }
public async Task YoutubeClient_GetMediaStreamAsync_Test(string videoId) { var client = new YoutubeClient(); var mediaStreamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoId); foreach (var streamInfo in mediaStreamInfoSet.GetAll()) { using (var stream = await client.GetMediaStreamAsync(streamInfo)) { Assert.That(stream, Is.Not.Null); var buffer = new byte[100]; await stream.ReadAsync(buffer, 0, buffer.Length); } } }
public async Task SendAudio(IGuild g, IMessageChannel c, string input) { var yt = new YoutubeClient(); if (input.ToLower().Contains("youtube.com")) { input = YoutubeClient.ParseVideoId(input); } else { var res = await yt.SearchAsync(input); input = res.FirstOrDefault(); } var vInfo = await yt.GetVideoInfoAsync(input); var vStreams = vInfo.AudioStreams.OrderBy(x => x.Bitrate).Last(); var vTitle = vInfo.Title; FilePath = $@"{BasePath}{g.Id}/{vTitle}.{vStreams.Container.GetFileExtension()}"; if (!Directory.Exists(BasePath + g.Id)) { Directory.CreateDirectory(BasePath + g.Id); } if (!File.Exists(FilePath)) { using (var goIn = await yt.GetMediaStreamAsync(vStreams)) using (var goOut = File.Create(FilePath)) await goIn.CopyToAsync(goOut); } if (ConnectedChannels.TryGetValue(g.Id, out IAudioClient _client)) { var dStream = _client.CreatePCMStream(AudioApplication.Music); await CreateStream(FilePath, g.Id).StandardOutput.BaseStream.CopyToAsync(dStream); await dStream.FlushAsync(); } }
private async Task <Stream> RefreshStream(Stream stream) { stream?.Dispose(); int retries = 0; while (retries < 10) { try { if (sourceStream != null && sourceStream is MediaStream) { return(await youtubeClient.GetMediaStreamAsync(videoQuality)); } else if (sourceUrl != null) { break; //Todo: for some reason this doesn't work (the stream.ReadAsync in DownloadFromStream still throws an Exception) //var request = (HttpWebRequest)WebRequest.Create(sourceUrl); //request.Method = "GET"; //request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"; //using (var response = await request.GetResponseAsync()) //{ // return response.GetResponseStream(); //} } } catch { retries++; if (retries == 10) { throw; } } } return(null); }
public async Task YoutubeClient_GetMediaStreamAsync_CannotEmbed_Test() { var client = new YoutubeClient(); var videoInfo = await client.GetVideoInfoAsync("_kmeFXjjGfk"); var streams = new List <MediaStreamInfo>(); streams.AddRange(videoInfo.MixedStreams); streams.AddRange(videoInfo.AudioStreams); streams.AddRange(videoInfo.VideoStreams); foreach (var streamInfo in streams) { using (var stream = await client.GetMediaStreamAsync(streamInfo)) { Assert.That.IsSet(stream); var buffer = new byte[100]; await stream.ReadAsync(buffer, 0, buffer.Length); } } }
///private string blabla = Startup.Configuration["aaa:aaa"]; public async Task <Stream> GetYoutubeAudioStreamAsync(string url) { var cli = new WebClient(); var id = YoutubeClient.ParseVideoId(url); var client = new YoutubeClient(); // Get metadata for all streams in this video var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(id); // Select one of the streams var streamInfo = streamInfoSet.Audio; byte[] buff; using (var fs = await client.GetMediaStreamAsync(streamInfo.FirstOrDefault(c => c.Container == Container.Mp4))) { var br = new BinaryReader(fs); long numBytes = fs.Length; buff = br.ReadBytes((int)numBytes); } return(new MemoryStream(buff)); }
public async Task YoutubeClient_GetMediaStreamAsync_Test() { string id = (string)TestContext.DataRow["Id"]; var client = new YoutubeClient(); var videoInfo = await client.GetVideoInfoAsync(id); var streams = new List <MediaStreamInfo>(); streams.AddRange(videoInfo.MixedStreams); streams.AddRange(videoInfo.AudioStreams); streams.AddRange(videoInfo.VideoStreams); foreach (var streamInfo in streams) { using (var stream = await client.GetMediaStreamAsync(streamInfo)) { Assert.That.IsSet(stream); var buffer = new byte[100]; await stream.ReadAsync(buffer, 0, buffer.Length); } } }
public async Task ytDownloadVid(string videoURL, string filetype = "mp3") { DateTime timerStart = DateTime.Now; var embed = new EmbedBuilder() .WithThumbnailUrl(config["icons:loading_url"]) .WithTitle(config["strings:start_get_video"]) .WithColor(Color.Blue); var loadingMessage = await Context.Channel.SendMessageAsync(embed : embed.Build()); Uri videoURI = new Uri(videoURL, UriKind.Absolute); var id = YoutubeClient.ParseVideoId(videoURI.ToString()); // TODO: Add proper URI error handling. //if (videoURI.Host != ) // throw new ArgumentException("Address provided is not a YouTube URI."); var ytClient = new YoutubeClient(); var ytMetadata = await ytClient.GetVideoAsync(id); if (ytMetadata.Duration > new TimeSpan(1, 0, 0)) { embed.WithColor(Color.Red) .WithThumbnailUrl(config["icons:error_url"]) .WithTitle(config["strings:max_duration_exceeded_title"]) .WithDescription(config["strings:max_duration_exceeded_desc"]); await loadingMessage.ModifyAsync(msg => msg.Embed = embed.Build()); return; } var ytStreamMetadataSet = await ytClient.GetVideoMediaStreamInfosAsync(id); var ytStreamMetadata = ytStreamMetadataSet.Audio.WithHighestBitrate(); var ytStreamTask = ytClient.GetMediaStreamAsync(ytStreamMetadata); var ytStream = await ytStreamTask; if (config.GetValue <bool>("debug", false)) { if (ytStreamTask.IsCompletedSuccessfully) { Console.WriteLine($"Successfully got stream data for video id \"{ytMetadata.Id}\""); } else { Console.WriteLine($"Failed to get stream data for video id \"{ytMetadata.Id}\""); } } var encodedStream = new MemoryStream(); using (Process ffmpeg = new Process { StartInfo = { FileName = config["ffmpeg_location"], Arguments = $"-i - -f {filetype} pipe:1", RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, }, EnableRaisingEvents = true }) { Exception ffmpegException = null; if (config.GetValue <bool>("debug", false)) { ffmpeg.ErrorDataReceived += (sender, eventArgs) => Console.WriteLine(eventArgs.Data); } ffmpeg.Start(); ffmpeg.BeginErrorReadLine(); var inputTask = Task.Run(() => { try { ytStream.CopyTo(ffmpeg.StandardInput.BaseStream); ffmpeg.StandardInput.Close(); } catch (IOException e) { ffmpegException = e; } }); var outputTask = ffmpeg.StandardOutput.BaseStream.CopyToAsync(encodedStream); Task.WaitAll(inputTask, outputTask); if (ffmpegException != null) { embed.WithColor(Color.Red) .WithThumbnailUrl(config["icons:error_url"]) .WithTitle(config["strings:ffmpeg_exception_title"]) .WithDescription(config["strings:ffmpeg_exception_description"]) .WithFields( new EmbedFieldBuilder() .WithName("*Stack Traceback:*") .WithValue(Format.Sanitize(ffmpegException.StackTrace)) .WithIsInline(false) ); await loadingMessage.ModifyAsync(msg => msg.Embed = embed.Build()); return; } ffmpeg.WaitForExit(); //var fileExt = MimeGuesser.GuessExtension(encodedStream); } Discord.Rest.RestUserMessage finishedMessage = null; if (encodedStream.Length < 0x800000) { if (config.GetValue <bool>("debug", false)) { Console.WriteLine("Uploading transcoded file to Discord."); } encodedStream.Position = 0; finishedMessage = await Context.Channel.SendFileAsync( encodedStream, $"{ytMetadata.Title}.{filetype}", embed : buildYtEmbed(ytMetadata) ); } else { if (config.GetValue <bool>("debug", false)) { Console.WriteLine("Uploading transcoded file to alternate host."); } embed.WithTitle(config["strings:file_too_large_title"]) .WithDescription(config["strings:file_too_large_description"]); await loadingMessage.ModifyAsync(msg => msg.Embed = embed.Build()); var newName = String.Join( "_", ytMetadata.Title.Split(Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries) ).TrimEnd('.'); using (HttpClient client = new HttpClient { BaseAddress = new Uri(config["http_put_url"]) }) { using (var response = client.PutAsync($"{newName}.{filetype}", new StreamContent(encodedStream))) { /* * DateTime lastUpdate = DateTime.Now; * while (response.Status == TaskStatus.Running) * { * if (DateTime.Now.Subtract(lastUpdate).TotalSeconds > 3) * { * await loadingMessage.ModifyAsync( * msg => msg.Content = $"Uploading to an alternate host...\nPlease allow time for this to finish.\n{}% uploaded..." * ); * lastUpdate = DateTime.Now; * } * } */ if (response.Result.IsSuccessStatusCode) { finishedMessage = await Context.Channel.SendMessageAsync( embed : buildYtEmbed( ytMetadata, new EmbedFieldBuilder() .WithName(config["strings:external_download_title"]) .WithValue(String.Format(config["strings:external_download_description"], await response.Result.Content.ReadAsStringAsync())) ) ); } } } } embed.WithColor(Color.Green) .WithThumbnailUrl(config["icons:success_url"]) .WithTitle(config["strings:finished_message_description"]) .WithDescription( $"[{config["strings:finished_message_link"]}](https://discordapp.com/channels/{Context.Guild.Id}/{Context.Channel.Id}/{finishedMessage.Id})" ); if (config.GetValue <bool>("debug", false)) { Console.WriteLine($"Successfully handled video id \"{ytMetadata.Id}\" in {DateTime.Now.Subtract(timerStart).Seconds} seconds."); } await loadingMessage.ModifyAsync(msg => msg.Embed = embed.Build()); Task.WaitAll(ytStream.DisposeAsync().AsTask(), encodedStream.DisposeAsync().AsTask()); }
public async Task SendAudioAsync(IGuild guild, IMessageChannel channel, string userInput) { var ytc = new YoutubeClient(); if (userInput.ToLower().Contains("youtube.com") || userInput.ToLower().Contains("youtu.be")) { userInput = YoutubeClient.ParseVideoId(userInput); } else { var searchList = await ytc.SearchAsync(userInput); userInput = searchList.First(); } var videoInfo = await ytc.GetVideoInfoAsync(userInput); var asi = videoInfo.AudioStreams.OrderBy(x => x.Bitrate).Last(); var title = videoInfo.Title; var rgx = new Regex("[^a-zA-Z0-9 -]"); title = rgx.Replace(title, ""); var path = $@"C:\Users\jack\Documents\Visual Studio 2017\Projects\jackbot2.0\jackbot2.0\music\{guild.Id}\{title}.{asi.Container.GetFileExtension()}"; await channel.SendMessageAsync("checking path"); if (!Directory.Exists($@"C:\Users\jack\Documents\Visual Studio 2017\Projects\jackbot2.0\jackbot2.0\music\{guild.Id}")) { Directory.CreateDirectory($@"C:\Users\jack\Documents\Visual Studio 2017\Projects\jackbot2.0\jackbot2.0\music\{guild.Id}"); } if (!File.Exists(path)) { var embed = new EmbedBuilder() { Title = $"Attempting to download", Description = $"{title}", Color = new Color(255, 0, 255) }; await channel.SendMessageAsync($"", embed : embed.Build()); using (var input = await ytc.GetMediaStreamAsync(asi)) using (var Out = File.Create(path)) { await input.CopyToAsync(Out); } } if (_connectedChannels.TryGetValue(guild.Id, out IAudioClient audioClient)) { var embed = new EmbedBuilder() { Title = $"Now playing", Description = $"**{title}**\n**Duration**: {videoInfo.Duration}\n**Views**: {videoInfo.ViewCount}\n<:like:325971963078115328>{videoInfo.LikeCount} | <:dislike:325971963451408386> {videoInfo.DislikeCount}", Color = new Color(255, 0, 255), ThumbnailUrl = videoInfo.ImageMaxResUrl }; await channel.SendMessageAsync("", embed : embed.Build()); var output = CreateStream(path).StandardOutput.BaseStream; var discordStream = audioClient.CreatePCMStream(AudioApplication.Music, 94208, 2000); var Config = GuildHandler.GuildConfigs[guild.Id]; Config.musicid.name = title; Config.musicid.added = DateTime.UtcNow; Config.musicid.duration = videoInfo.Duration.ToString(); Config.musicid.seconds = videoInfo.Duration.TotalSeconds; Config.musicid.thumbnail = $"https://img.youtube.com/vi/{videoInfo.Id}/maxresdefault.jpg"; GuildHandler.GuildConfigs[guild.Id] = Config; await GuildHandler.SaveAsync(GuildHandler.GuildConfigs); await output.CopyToAsync(discordStream); await discordStream.FlushAsync(); File.Delete(path); } }
public async Task SendAudioAsync(IGuild Guild, string UserInput) { var YTC = new YoutubeClient(); if (UserInput.ToLower().Contains("youtube.com")) { UserInput = YoutubeClient.ParseVideoId(UserInput); } else { //var SearchList = await YTC.SearchAsync( UserInput ); HttpClient _httpClient = new HttpClient(); string EncodedSearchQuery = WebUtility.UrlEncode(UserInput); string Request = $"https://www.youtube.com/search_ajax?style=xml&search_query={EncodedSearchQuery}"; var Response = await _httpClient.GetStringAsync(Request).ConfigureAwait(false); var SearchResultsXml = XElement.Parse(Response).StripNamespaces(); var VideoIds = SearchResultsXml.Descendants("encrypted_id").Select(e => ( string )e); UserInput = VideoIds.First(); } var MediaInfo = await YTC.GetVideoMediaStreamInfosAsync(UserInput); var ASI = MediaInfo.Audio.OrderBy(x => x.Bitrate).Last(); var VideoInfo = await YTC.GetVideoAsync(UserInput); var Title = VideoInfo.Title; //VideoInfo.ToString(); ; var RGX = new Regex("[^a-zA-Z0-9 -]"); Title = RGX.Replace(Title, ""); var Name = $"{Title}.{ASI.AudioEncoding.ToString()}"; #if DEBUG var Path = "bin/Debug/netcoreapp1.1/Songs/"; #else String Path = "Songs/"; #endif if (!File.Exists(Path + Name)) { using (var Input = await YTC.GetMediaStreamAsync(ASI)) { Directory.CreateDirectory(Path); using (var Out = File.Create(Path + Name)) { await Input.CopyToAsync(Out); } } } IAudioClient AudioClient; await JukeBot.DiscordClient.SetGameAsync(Title); if (this.ConnectedChannels.TryGetValue(Guild.Id, out AudioClient)) { var Output = this.CreateStream(Path + Name).StandardOutput.BaseStream; this.AudioData = new MemoryStream(); await Output.CopyToAsync(this.AudioData); await Output.FlushAsync(); Output.Dispose(); int read_length = 0; bool flipflop = false; int buffer_size = 2048; var buffer = new[] { new byte[buffer_size], new byte[buffer_size] }; this.AudioData.Seek(0x0, SeekOrigin.Begin); var DiscordStream = AudioClient.CreatePCMStream(AudioApplication.Music, 2880); Task writer; Task <int> reader; while (this.AudioData.Position < this.AudioData.Length) { if (!this.Pause) { writer = DiscordStream.WriteAsync(buffer[flipflop ? 0 : 1], 0, read_length); flipflop = !flipflop; reader = this.AudioData.ReadAsync(buffer[flipflop ? 0 : 1], 0, buffer_size); read_length = await reader; await writer; } else { await DiscordStream.WriteAsync(new byte[512], 0, 512); read_length = 0; } } await this.AudioData.FlushAsync(); //await Output.CopyToAsync(DiscordStream); await DiscordStream.FlushAsync(); await JukeBot.DiscordClient.SetGameAsync(""); } }
private async Task SendAudio(AudioStreamInfo streamInfo, YoutubeExplode.Models.Video video) { using (var audioStream = await _youtubeClient.GetMediaStreamAsync(streamInfo)) await TelegramClient.SendAudioAsync(ChatId, audioStream, video.Title, ParseMode.Default, (int)video.Duration.TotalSeconds, video.Author, title : video.Title); }
private async void DownloadAudio(int position, string path) { if (position < 0 || position > queue.Count || queue[position].State != DownloadState.None) { return; } System.Console.WriteLine("&Downloading audio of: " + queue[position].Name); queue[position].State = DownloadState.Initialization; UpdateList(position); while (downloadCount >= maxDownload) { await Task.Delay(1000); } downloadCount++; currentStrike++; CreateNotification(queue[position].Name); try { YoutubeClient client = new YoutubeClient(); Video video = await client.GetVideoAsync(queue[position].YoutubeID); MediaStreamInfoSet mediaStreamInfo = await client.GetVideoMediaStreamInfosAsync(queue[position].YoutubeID); MediaStreamInfo streamInfo; if (mediaStreamInfo.Audio.Count > 0) { streamInfo = mediaStreamInfo.Audio.Where(x => x.Container == Container.Mp4).OrderBy(s => s.Bitrate).Last(); } else if (mediaStreamInfo.Muxed.Count > 0) { streamInfo = mediaStreamInfo.Muxed.Where(x => x.Container == Container.Mp4).OrderBy(x => x.Resolution).Last(); } else { queue[position].State = DownloadState.Error; downloadCount--; if (queue.Count != 0) { DownloadAudio(queue.FindIndex(x => x.State == DownloadState.None), path); } Playlist.instance?.Activity.RunOnUiThread(() => { Playlist.instance.CheckForSync(); }); return; } queue[position].State = DownloadState.Downloading; UpdateList(position); string title = video.Title; foreach (char c in Path.GetInvalidFileNameChars()) //Make the title a valid filename (remove /, \, : etc). { title = title.Replace(c, ' '); } string fileExtension = "m4a"; //audio only extension containing aac (audio codex of the mp4) string outpath = path; if (queue[position].PlaylistName != null) { outpath = Path.Combine(path, queue[position].PlaylistName); Directory.CreateDirectory(outpath); } string filePath = Path.Combine(outpath, title + "." + fileExtension); if (File.Exists(filePath)) { int i = 1; string defaultPath = filePath; do { filePath = Path.Combine(outpath, title + " (" + i + ")." + fileExtension); i++; }while (File.Exists(filePath)); } MediaStream input = await client.GetMediaStreamAsync(streamInfo); queue[position].Path = filePath; files.Add(filePath); FileStream output = File.Create(filePath); byte[] buffer = new byte[4096]; int byteReaded = 0; while (byteReaded < input.Length) { int read = await input.ReadAsync(buffer, 0, 4096); await output.WriteAsync(buffer, 0, read); byteReaded += read; UpdateProgressBar(position, byteReaded / input.Length); } output.Dispose(); queue[position].State = DownloadState.MetaData; UpdateList(position); if (queue.Count == 1) { SetNotificationProgress(100, true); } SetMetaData(position, video.Title, video.Author, video.Thumbnails); files.Remove(filePath); downloadCount--; if (queue.Count != 0) { DownloadAudio(queue.FindIndex(x => x.State == DownloadState.None), path); } Playlist.instance?.Activity.RunOnUiThread(() => { Playlist.instance.CheckForSync(); }); } catch (System.Net.Http.HttpRequestException) { MainActivity.instance.Timout(); Cancel(); } catch (DirectoryNotFoundException) { Handler handler = new Handler(Looper.MainLooper); handler.Post(() => { Toast.MakeText(Application.Context, Resource.String.download_path_error, ToastLength.Long).Show(); }); Cancel(); } catch { MainActivity.instance.UnknowError(ErrorCode.DL1); Cancel(); } }
public Task <MediaStream> GetStreamAsync(MediaStreamInfo info) { return(youtubeClient.GetMediaStreamAsync(info)); }