Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
Время на прочтение5 мин
Количество просмотров397K
Видеохостинг YouTube — второй по посещаемости сайт в мире. Его смотрят с умных телевизоров, игровых и телевизионных приставок, настольных компьютеров и ноутбуков, планшетов и смартфонов. Не все из этих устройств требуют одинаковой картинки. Сетевая природа сервиса и потокового видео предполагает, что на сайте должны быть доступны опции просмотра в разном качестве.
Качество картинки на YouTube варьируется от 144p (144 строчки в прогрессивной развёртке) до 8K 4320p. Последнее видео в четыре раза крупнее 4К 2160p, в шестнадцать — 1080p, в тридцать шесть — 720p, который также называют HD.
Мало какой компьютер может проиграть это видео в его полном разрешении, а доступных по цене 8K-мониторов в мире просто нет.
Технология MPEG-DASH разбивает контент на куски, а браузер запрашивает эти сегменты автоматически. Логично хранить и отдавать отдельно видео и звук. У DASH есть жирный плюс: адаптивность воспроизведения.
Несколько лет назад пользователи YouTube заметили введение DASH по тому, что буферизация видео больше не шла до конца ролика, а ограничивалась примерно минутой. Около того же времени другая проблема возникла у скачивающих видео с YouTube. Внезапно обнаружилось, что ролики с качеством 1080p доступны в виде файлов без звука. Сайты-сервисы, которые раньше выдавали ссылки на скачивание видео, отдавали лишь 720p, не выше. Около 1080p стояло «без звука» или «только видео».
Простое решение: скачать файл видео, скачать файл звука и объединить их с помощью, к примеру, FFmpeg. Сайты скачивания на это не решились: для этого нужен трафик, дисковое пространство для хранения, наконец, можно получить бан по IP от самого YouTube. Подобные сервисы живут на доходах от баннеров, а на эти деньги подобное не позволить.
Проблему можно решить на стороне клиента. Пользователю же нужно разобраться, как скачать исходные данные с YouTube, определиться с их качеством и выбрать лучшие варианты. Видео хранится в VP9 и MP4, звук — M4A, Vorbis или Opus в WebM. Есть много вариантов с разным битрейтом. После этого нужно сшить всё в контейнер .mp4 или .mkv. В зависимости от выбранных форматов команда для FFmpeg может выглядеть как ffmpeg -i videoplayback.mp4 -i videoplayback.webm -c:v copy -c:a copy videoplayback.mkv
, где videoplayback.mkv — наш готовый файл.
Процесс однообразен, почему бы его не автоматизировать? Есть утилита, которая выполняет всё это самостоятельно и поддерживает ещё несколько видеохостингов.
youtube-dl
youtube-dl — кроссплатформенный свободный проект с открытым исходным кодом на Python. Разработку начал Рикардо Гарсиа, сегодня проект ведут несколько контрибьюторов.
На странице скачивания доступны версия для Windows и инструкции по установке для UNIX-подобных систем (Linux, OS X, FreeBSD и прочие). Для работы в Windows обязательно наличие Microsoft Visual C++ 2010 Redistributable Package x86, для всех остальных — версия Python 2.6, 2.7, 3.2 или выше.
youtube-dl есть в каталогах пакетов некоторых дистрибутивов Linux: sudo apt-get install youtube-dl
, sudo yum install youtube-dl
, sudo pacman -S youtube-dl
— всё это должно установить утилиту. Вернее, одну из её версий, которые быстро устаревают. Логичнее установить python-pip
, а затем устанавливать оттуда: sudo pip install youtube-dl
. Для сравнения: на момент написания статьи в репозиториях Debian лежит версия 2014.08.05, в то время как актуальной является 2016.11.4.
Часть из дальнейших инструкций относится только к пользователям на Windows 10, но общие принципы работают везде. Переместите скачанный файл youtube-dl.exe
в любую папку, к примеру, создайте папку Downloads
в Videos
. В «Проводнике» в меню «Файл» откройте «Командную строку».
Итак, чтобы выкачать видео в максимальном разрешении и с наилучшим звуком, необходимо ввести команду вида
youtube-dl https://www.youtube.com/watch?v=miVRaoR_8xQ
То есть нужна ссылка на страницу с роликом. В Windows 10 в «Командной строке» работает вставка по Ctrl + V. В более ранних версиях нужно правым щелчком мыши открыть контекстное меню и выбрать пункт меню «Вставить».
Скачивание плейлистов происходит аналогичным образом. Формат ссылки на плейлист — https://www.youtube.com/playlist?list=PL94A83DC128CC6B4B
, то есть нужно зайти на главную страницу плейлиста. Осторожно: youtube-dl выкачает все видео в плейлисте.
Можно выкачать все видео пользователя: нужно лишь подставить ссылку на канал в виде https://www.youtube.com/user/username
.
По флагу -F
будут показаны все доступные форматы. Если ввести флаг -f
с числовым кодом формата, он будет выкачан. Комбинация -f bestaudio
выкачает аудио в лучшем формате.
Процесс выкачивания 981 роликов в виде аудио с канала корейской АСМР-щицы.
Одним YouTube дело не ограничивается: программа умеет качать с большого числа сайтов. Если закачку прервать по Ctrl + C, а затем начать снова, утилита распознает недокачанный фрагмент и начнёт качать остаток.
Видеосервисы регулярно обновляют свои плееры, часть борется с «качальщиками», youtube-dl добавляет в список поддерживаемых новые и новые сайты. Поэтому иногда желательно обновляться. В самостоятельно выкачанных версиях обновление выполняется по youtube-dl -U
(sudo
по необходимости). В случае pip нужно запустить sudo pip install -U youtube-dl
.
» Официальная документация youtube-dl
Аналоги
В качестве аналога небольшой свободной утилитки без графического интерфейса можно привести Freemake Video Downloader. Этот софт содержит эталонный набор отвратительных практик дешёвого софта для Windows.
На странице скачивания продукт рекламируется как бесплатный. Как это часто случается, в дополнение к самой программе инсталлятор пытается поставить сторонний продукт. Это уже настолько привычно, что стало нормой. Установки ненужностей можно избежать только, если выбрать установку с опциями. Лучше всего установщик не запускать вообще: программу обвиняли в подкидывании троянов, шпионского ПО и adware даже при снятии всех галочек.
Программа умеет скачивать видео со звуком с YouTube в разрешении в 1080p и выше. Есть лишь одна проблема: в бесплатной версии можно качать только на скорости в 4 мегабайта в секунду. Чтобы снять ограничение, нужно выложить 10 долларов. Всё это немного противоречит заявлениям о бесплатности. Сам интерфейс программы безвкусен и содержит много рекламы других продуктов фирмы-изготовителя.
Другой подобный софт для выкачивания видео выполняет тривиальную задачу, но требует плату за снятие ограничений. Добросовестным можно назвать разве что Free Download Manager, но его возможности по скачиванию видео слабее: нет поддержки плейлистов и каналов, список поддерживаемых сайтов ограничивается YouTube и Google Videos.
На самом деле этот пост не про конкретную программу, которая что-то умеет. И не про то, что консольные приложения лучше.
Современный пользователь приобрёл положительную привычку: когда ему нужно решить некую проблему, он набирает её описание в поисковой системе и тыкается в результаты на первой странице. За более чем полтора десятка лет существования поисковых систем и благодаря расцвету систем искусственного интеллекта вопрос «убрать морщинки» гарантированно выдаст пять—десять статей, которые почти всегда решат проблему.
На другом конце появилась другая хорошая привычка: писать софт для Windows, который решает задачу, которую можно описать с помощью поискового запроса. К примеру, «скачать видео youtube 1080p». Подобных запросов у пользователей много. Можно наделать программ под каждый из них, предоставлять бесплатную версию с возможностью апгрейда до полной за 10—30 долларов. Или продавать установки: распространять с программой нежелательный софт или вообще вирусы.
Есть прекрасный бесплатный софт с открытыми исходными кодами, который решает эти, возникающие у пользователей, запросы. Но поисковая оптимизация никогда не даст ему поселиться на первых строчках выдачи. Там сидят разнообразные программы сомнительного происхождения. Они не внушают доверия ни качеством, ни тем, что подсунет инсталлятор. В этом и есть трагедия жизни полезного софта уровня youtube-dl.
I’ve always been fascinated with how YouTube encodes the endless hours of videos uploaded to the site. YouTube employs the best and the brightest and their task is positively Sisyphean.
Jan Ozer develops training courses for streaming media professionals; provides encoding-related testing services to encoder developers; helps video producers perfect their encoding ladders and deploy new codecs. Jan blogs primarily at the Streaming Learning Center.
For years, I’ve gotten a glimpse of YouTube’s encoding practices via download tools like the Wondershare Uniconverter, but it’s always been a very restrictive view. Recently, I learned of a tool called youtube-dl, which reveals how YouTube encodes every file that they make available on the service, every rung, every codec, audio, video, and subtitles. For a researcher like myself, it was (to paraphrase Springsteen and show my age yet again), like finding the keys to the universe in the engine of an old parked car.
This article identifies what youtube-dl is and details how to perform some basic operations.
Table of Contents
About youtube-dl
As stated here:
youtube-dl is a command-line program to download videos from YouTube.com and a few more sites. It requires the Python interpreter (2.6, 2.7, or 3.2+), and it is not platform-specific. We also provide a Windows executable that includes Python. youtube-dl should work in your Unix box, in Windows, or in Mac OS X. It is released to the public domain, which means you can modify it, redistribute it or use it however you like.
More specifically, youtube-dl
downloads the individual fragments that make up the audio and video and then consolidates them into a single file. Here’s a list of over 700 sites that youtube-dl
supports, which includes Vimeo and Udemy, though I only tested on YouTube.
Note that youtube-dl
does not “crack” files encrypted with PlayReady, Widevine, or presumably FairPlay, so if the video files are encrypted with these technologies, you may be able to download them but the result won’t be playable. Again, I tested only on YouTube and didn’t encounter any encrypted files.
There are many tools that let you download videos from YouTube. What’s special about youtube-dl
is that:
- You can generate a file list of all encodes performed by YouTube for a particular file, which I find useful for research (see here).
- You can download the specific file that you want to download; so, if you want the 1080p AV1 version, you can.
Downloading youtube-dl
You can download youtube-dl
here. I downloaded the Windows version mentioned so I didn’t need Python installed (though it was). Installation for other platforms is covered on the linked page. If you need more detailed help on getting the program installed, check here.
Note that some articles on youtube-dl
indicate that FFmpeg is needed, which makes sense during the file consolidation phase. I have FFmpeg installed at c:\ffmpeg\bin
on my test computer and it’s in the file path, so presumably, youtube-dl
could easily find it. However, when I changed the folder to ffmpegx and didn’t update the path youtube-dl worked as normal. So, I’m not sure if you need FFmpeg installed or not.
Here’s the program documentation which is very well organized and specific. If you’ll be experimenting with multiple functions you’ll want to print this out.
Default Operation
There’s an extensive and useful discussion here on what comprises a youtube-dl
command string and the program’s core functions. I’m just going to cover a very basic feature set that I found very useful in my research.
Downloading a Video
Navigate to the YouTube video that you want to download. Let’s work with this video:
To download the highest quality video iteration, use this string :
youtube-dl.exe https://youtu.be/hWbCSAcNOCU
Here, you’re calling the command and listing the URL of the YouTube video to download. Here’s what it looks like in the Command window.
The program downloads Jan Ozer - MPEG-DASH Explained and HTML5 Video-hWbCSAcNOCU.mp4
with the file details shown in Figure 2, most notably that the program downloads both video and audio and muxes it into a file that’s ready for viewing. Note that the file is H.264-encoded video and AAC-encoded audio.
I make a big point about both audio and video because when you download specific output files, as we’ll do in a moment, you only get that file, whether audio or video. If you take this route you’ll have to mux the files together manually (click here for a useful tutorial).
Downloading the File List
Now let’s download a list of all audio/video files encoded by YouTube for this file and save it locally in a file called jan.txt. Use this command adding the -F
.
youtube-dl.exe -F https://youtu.be/hWbCSAcNOCU > jan.txt
When we open jan.txt, we see the following information (you can download jan.txt here)
If you’re trying to figure out how YouTube encodes the files that are uploaded to the service, this data is the Rosetta Stone, with all format, codec, resolution, and data rate information. You see that in addition to the 720p MP4 file that youtube-dl downloaded above, there’s a WebM file encoded using VP9, which is file 247
. Let’s download that.
Download a Specific File
To download a specific file in the list, use the command string below.
youtube-dl.exe -f 247 https://youtu.be/hWbCSAcNOCU
This downloads the file shown in Figure 5, which as noted, is only video. If you want to add audio you’ll have to download that separately and then use FFmpeg to mux the two streams together.
Download Subtitles
To download the subtitles, use this command string. Note that write-auto-sub is YouTube only; check the documentation for commands for other services (which should be --write-sub
).
youtube-dl.exe --write-auto-sub https://youtu.be/hWbCSAcNOCU
The program downloads the VTT file shown in Figure 6.
That’s as far as I got with the program; which was all I needed to complete my research. As noted in several of the referenced articles, I’m barely scratching the surface, and youtube-dl
is capable of a whole lot more.
Jan Ozer
Develops training courses for streaming media professionals; provides encoding-related testing services to encoder developers; helps video producers perfect their encoding ladders and deploy new codecs. Jan blogs primarily at the Streaming Learning Center.
Вы тут: Главная → Popular → Как скачать видео с YouTube с помощью youtube-dl и PowerShell
Меня тут попросили помочь скачать несколько видео с YouTube. То ли онлайн-сервисы не справлялись, то ли еще что — не суть важно. Усложнять процесс дальше копирования ссылки на видео в буфер обмена было нежелательно, но в выборе инструментов меня ничто не ограничивало.
Я не раздумывая выбрал youtube-dl и PowerShell:
youtube-dl.exe $(Get-Clipboard)
PowerShell подставляет URL из буфера обмена в качестве параметра youtube-dl (о прочих параметрах чуть ниже). Путь к утилите нужно указать полностью или прописать в PATH. Команду я поместил в CMD-файл, чтобы не менять политики скриптов, а закачку можно было запускать одним щелчком.
powershell -ExecutionPolicy Bypass -noprofile -command youtube-dl.exe $(Get-Clipboard)
Все работало, но сразу проявился нюанс. Если видео проигрывается из плейлиста, то он выкачается целиком, что по условиям моей задачи было нежелательно. В этом случае URL ролика имеет примерно такой вид:
https://www.youtube.com/watch?v=asdf&list=asdf
Можно разбить строку с помощью метода .NET split(), используя в качестве разделителя амперсанд.
youtube-dl.exe $(Get-Clipboard).split('&')[0]
Теперь в качестве параметра утилите передается только та часть URL, которая предваряет амперсанд. На этот вариант жалоб не поступало, и я счел задачу решенной.
Здесь я хочу передать привет Василию Гусеву. Еще в 2008 году он опубликовал в своем блоге запись про Join и Split, и она идеально подходит к этому посту в качестве дополнительного материала.
Запись не столько про скачивание видео с YouTube, сколько про PowerShell — работу с буфером обмена, разделение строки и выполнение отдельных команд PowerShell без ограничений политик. Обособленный вызов команд требуется достаточно часто, и вот недавний пример из форума в контексте запуска из планировщка.
В youtube-dl лучшее качество видео и аудио достигается раздельной загрузкой потоков и объединением их в файл, например, с помощью утилиты ffmpeg, помещенной в PATH. Это стандартное поведение youtube-dl, т.е. достаточно только указать URL.
youtube-dl URL
Читайте также комментарии — там много полезных советов.
Are you looking for the easiest way to download videos from YouTube? You’ve come to the right place! In this article, I’ll explain how you can use youtube-dl – a powerful command line program – to quickly and easily download any video from YouTube.
This is an especially important skill if you want to save your favorite tutorials or study for exams with lecture recordings. I have been researching and using youtube-dl myself for quite some time now, so I know what it takes and how to get it done efficiently. With my expertise, you will be downloading videos like a pro in no time at all!
Whether you are a beginner just trying out new things or an experienced user searching for the best alternative to downloading videos, this guide has something for everyone. Plus, after reading this article, not only will you learn how to use youtube-dl but also which files types work best with different devices! So let’s dive in and start downloading today!
Installing YouTube-dl: A Step-by-Step Guide
YouTube-dl is a free and open-source software that allows users to download videos from various websites, including YouTube. This tool is especially useful for those who want to watch content without needing an internet connection or access it when offline. In this step-by-step guide, we will outline how to install YouTube-dl on Windows.
1. Download Python
Before you can install YouTube-dl, you need to download Python, an interpreter programming language used in the development of web applications and scripts. Visit the official website (https://www.python.org/downloads/windows/) and select your operating system version. Once downloaded, run the installer and follow instructions.
2. Open Command Prompt
After installing Python on your computer successfully, press “Windows + R” key at once; type “cmd”, then click “OK.” The command prompt window will appear on your screen.
3. Install Youtube-DL
To install youtube-dl using python package manager pip type or copy-paste these commands one by one:
– pip install -U youtube_dl
Congratulations! You now have installed YouTube-dl on your windows device successfully!
Overall, with this simple guide readily available for anyone who wants it, downloading videos from sites like YouTube has never been easier thanks to the helpful tools provided by open-source software developers around the world such as those behind youtube-dl’s creation.The ability to enjoy content even when not connected via WiFi or cellular data connections adds yet another level of convenience that only those who have experienced poor connectivity during travel can appreciate fully!
Understanding YouTube-dl Commands and Options
YouTube-dl is an open-source program that allows you to download videos from YouTube, Vimeo, and other websites. It is a powerful tool with many features and options that can be overwhelming for new users. In this article, we will go over some of the most useful commands and options that you can use with YouTube-dl.
One of the most basic commands you will need to know is how to download a video. To do this, simply enter “youtube-dl” followed by the URL of the video you want to download. For example: `youtube-dl https://www.youtube.com/watch?v=dQw4w9WgXcQ`. You can also specify where to save the file using -o flag: `youtube-dl -o “~/Videos/%(title)s-%(id)s.%(ext)s” https://www.youtube.com/watch?v=dQw4w9WgXcQ`
Another useful option is “-F”, which shows all available formats for a video. This command will display a list of available formats along with their resolution, format ID, and file extension. You can then choose which format you want to download using its respective format ID.
Lastly, if you encounter issues downloading certain videos due to region restrictions or age restrictions set by YouTube or any other platform, try adding proxy settings while running youtube_dl using –proxy flag followed by your proxy server’s IP address in HTTP/HTTPS protocol: `youtube_dl –proxy http://your.proxy.server.ip http://some.site/video`.
In conclusion, understanding these YouTube-dl commands and options can help make your video downloading experience more efficient and effective. With practice on these commands along with others not mentioned here like “–playlist-start” or skipping unwanted parts through “–start-time/–end-time,” one may customize their downloading behavior accordingt o their preferences easily!
How to Download Videos from YouTube with the Best Quality and Format Settings
YouTube is the go-to source for millions of people worldwide to watch videos online. However, there are times when you want to download a video from YouTube and watch it offline on your device. The process of downloading YouTube videos can be quite complicated, but with some tips and tricks, you can download them with ease.
Firstly, to get the best quality and format settings while downloading a video from YouTube, use a reliable downloader like 4K Video Downloader or ClipGrab which are free to use and provide excellent results. Secondly, before downloading the video decide on what format works best for you – MP4 is compatible with most devices whereas AVI may not be supported by all devices.
Lastly, ensure that your internet connection speed is fast enough so that the download does not take too long. Once you have decided on these three things – down-loader program choice; preferred video format; Internet speed – just follow these steps:
1) Copy the link/URL from the YouTube page where your desired video appears.
2) Open your chosen downloader program.
3) Click ‘paste URL’ in the program’s options or simply paste it in if prompted directly.
4) Select ‘download’ once details such as file size & duration appear
5) Save your downloaded file into storage
6) Enjoy watching it offline whenever you want!
In conclusion: To get high-quality downloaded videos from YouTube ensure that you select an appropriate downloader tool suitable for both Windows and Mac operating systems. Determine which preferred format works best for viewing on one’s device(s), whether it be MP4 or otherwise. Lastly ensure consistent & stable internet connection speeds throughout!
Troubleshooting Common Issues When Using YouTube-dl for Video Downloads
YouTube-dl is a powerful command-line tool that allows users to download videos from various websites, including YouTube. However, like any other software, it can sometimes run into issues that prevent it from working as expected. In this article, we will discuss some common problems that you may encounter when using YouTube-dl and the steps you can take to troubleshoot them.
One of the most frequent errors is “ERROR: unable to download video data” message. This error usually occurs when there is an issue with your internet connection or if the website hosting the video has restricted access. The first thing you should do in this situation is to check your internet connectivity and try again after resolving any connectivity issues. If the problem persists even after ensuring stable connectivity, it might be due to restrictions set by the video’s hosting platform.
Another issue users face while downloading videos is getting an “incorrect password” error message during authentication. Often this happens because of outdated credentials or incorrect login details entered into youtube-dl configuration files saved on their computer system settings file. If this happens frequently during downloads process then reset passwords or update credentials promptly.
Lastly, another common challenge faced while using youtube-dl for video downloads are missing audio tracks due to wrong format selection at time of downloading; in situations such as these users must ensure they select correct formats suitable for both audio and visual components of desired content before initiatiating downmloads using Youtube-DL.
In conclusion ,YouTube-dl remains one of the most widely used tools for downloading videos online despite occasional challenges encountered by newbies who are just starting out on how best they can use its features efficiently without experiencing hitches along way . Properly troubleshooting these difficulties will help ensure smooth functionality whenever you want to download a specific type/format/quality content from web sources quickly and easily!
Advanced Tips and Tricks for Maximizing Your Use of YouTube-dl
YouTube-dl is a powerful tool that allows you to download videos and audio from various websites, including YouTube. But did you know that there are advanced tips and tricks that can help you get even more out of this handy software?
One useful trick is the ability to limit the download speed when using YouTube-dl. This can be helpful if you have limited bandwidth or want to avoid slowing down other applications on your computer while downloading. To do this, simply add the “–limit-rate” option followed by the desired maximum speed in bytes per second. For example, “–limit-rate 500k” would limit the download speed to 500 kilobytes per second.
Another tip is to use YouTube-dl with batch files or scripts for automating downloads of multiple videos at once. You can create a text file containing a list of URLs for each video you want to download, then use a batch script or shell command to run through all of them automatically. This saves time and effort compared to manually entering each URL one by one.
Finally, don’t forget about some of the lesser-known features of YouTube-dl, such as its support for subtitle extraction and metadata embedding. With these options enabled, you can not only download videos but also capture subtitles in different languages and attach relevant tags and descriptions for easier organization.
By taking advantage of these advanced tips and tricks for maximizing your use of YouTube-dl, you’ll be able to save time and streamline your workflow when it comes to downloading media from various online sources. So why not give it a try today?