Reputation: 25
I'm trying to retrieve the link for the audio only file on youtube using youtube_dl. I wonder if it's possible to do so. I'm using youtube_dl as in python code not with terminal.
Many thanks
Upvotes: 1
Views: 9951
Reputation:
Only a very small minority of the websites supported by youtube-dl actually serve audio-only files. But some do, including most videos on YouTube. For these, you can request the filetype bestaudio
and extract the information instead of downloading:
from __future__ import unicode_literals
import youtube_dl
ydl_opts = {
'format': 'bestaudio',
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(
'https://www.youtube.com/watch?v=BaW_jenozKc', download=False)
print(info['formats'][0]['url'])
Note that this will get you the correct URL. However, there is no guarantee that this URL will work, if you change anything of:
http_headers
key of the format dictionary.ydl.cookiejar
).Which of these constrains have to be met depends on the video, and is subject to sudden change. For instance, it looks like at the moment the URL is enough for many YouTube videos, but YouTube has definitely blocked other IPv4 addresses and even all different IP addresses for some videos, or only music and other highly monetized videos, over time.
Also note that the file you'll get may be in a strange format. For instance, YouTube used to send invalid m4a files which could not be read by most players. You'll often get opus, which may not be supported everywhere. If you just want the audio file, it's better to let youtube-dl download and convert it, as described in the documentation and other answers.
Upvotes: 6
Reputation: 237
This is a duplicate of an existing question here: download only audio from youtube video using youtube-dl in python script
However, I will be helpful and share the answer here. Use this code:
import youtube_dl
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(['insert youtube link here'])
It should convert the audio to an mp3 using ffmpeg. Refer here for further examples and instructions.
Upvotes: 0
Reputation: 2480
If you want to download the audio only, you can do this,
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'outtmpl': '%(title)s.%(etx)s',
'quiet': False
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([url]) # Download into the current working directory
This is a snippet of code I've taken out of a project I worked on. You can see the full source here:https://github.com/francium/audiosave/blob/master/audiosave.py
You can see the API and docs for youtube_dl here: https://github.com/rg3/youtube-dl/blob/master/README.md#embedding-youtube-dl
Upvotes: 5