Skip to content

audio

Audio providers for spotdl.

AudioProvider(output_format='mp3', cookie_file=None, search_query=None, filter_results=True, yt_dlp_args=None) ¤

Base class for all other providers. Provides some common functionality. Handles the yt-dlp audio handler.

Arguments¤
  • output_directory: The directory to save the downloaded songs to.
  • output_format: The format to save the downloaded songs in.
  • cookie_file: The path to a file containing cookies to be used by YTDL.
  • search_query: The query to use when searching for songs.
  • filter_results: Whether to filter results.
Source code in spotdl/providers/audio/base.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def __init__(
    self,
    output_format: str = "mp3",
    cookie_file: Optional[str] = None,
    search_query: Optional[str] = None,
    filter_results: bool = True,
    yt_dlp_args: Optional[str] = None,
) -> None:
    """
    Base class for audio providers.

    ### Arguments
    - output_directory: The directory to save the downloaded songs to.
    - output_format: The format to save the downloaded songs in.
    - cookie_file: The path to a file containing cookies to be used by YTDL.
    - search_query: The query to use when searching for songs.
    - filter_results: Whether to filter results.
    """

    self.output_format = output_format
    self.cookie_file = cookie_file
    self.search_query = search_query
    self.filter_results = filter_results

    if self.output_format == "m4a":
        ytdl_format = "bestaudio[ext=m4a]/bestaudio/best"
    elif self.output_format == "opus":
        ytdl_format = "bestaudio[ext=webm]/bestaudio/best"
    else:
        ytdl_format = "bestaudio"

    yt_dlp_options = {
        "format": ytdl_format,
        "quiet": True,
        "no_warnings": True,
        "encoding": "UTF-8",
        "logger": YTDLLogger(),
        "cookiefile": self.cookie_file,
        "outtmpl": f"{get_temp_path()}/%(id)s.%(ext)s",
        "retries": 5,
    }

    if yt_dlp_args:
        user_options = args_to_ytdlp_options(shlex.split(yt_dlp_args))
        yt_dlp_options.update(user_options)

    self.audio_handler = YoutubeDL(yt_dlp_options)

name: str property ¤

Get the name of the provider.

Returns¤
  • The name of the provider.

get_best_result(results) ¤

Get the best match from the results using views and average match

Arguments¤
  • results: A dictionary of results and their scores
Returns¤
  • The best match URL and its score
Source code in spotdl/providers/audio/base.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
def get_best_result(self, results: Dict[Result, float]) -> Tuple[Result, float]:
    """
    Get the best match from the results
    using views and average match

    ### Arguments
    - results: A dictionary of results and their scores

    ### Returns
    - The best match URL and its score
    """

    best_results = get_best_matches(results, 8)

    # If we have only one result, return it
    if len(best_results) == 1:
        return best_results[0][0], best_results[0][1]

    # Initial best result based on the average match
    best_result = best_results[0]

    # If the best result has a score higher than 80%
    # and it's a isrc search, return it
    if best_result[1] > 80 and best_result[0].isrc_search:
        return best_result[0], best_result[1]

    # If we have more than one result,
    # return the one with the highest score
    # and most views
    if len(best_results) > 1:
        views: List[int] = []
        for best_result in best_results:
            if best_result[0].views:
                views.append(best_result[0].views)
            else:
                views.append(self.get_views(best_result[0].url))

        highest_views = max(views)
        lowest_views = min(views)

        if highest_views in (0, lowest_views):
            return best_result[0], best_result[1]

        weighted_results: List[Tuple[Result, float]] = []
        for index, best_result in enumerate(best_results):
            result_views = views[index]
            views_score = (
                (result_views - lowest_views) / (highest_views - lowest_views)
            ) * 15
            score = min(best_result[1] + views_score, 100)
            weighted_results.append((best_result[0], score))

        # Now we return the result with the highest score
        return max(weighted_results, key=lambda x: x[1])

    return best_result[0], best_result[1]

get_download_metadata(url, download=False) ¤

Get metadata for a download using yt-dlp.

Arguments¤
  • url: The url to get metadata for.
Returns¤
  • A dictionary containing the metadata.
Source code in spotdl/providers/audio/base.py
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
def get_download_metadata(self, url: str, download: bool = False) -> Dict:
    """
    Get metadata for a download using yt-dlp.

    ### Arguments
    - url: The url to get metadata for.

    ### Returns
    - A dictionary containing the metadata.
    """

    try:
        data = self.audio_handler.extract_info(url, download=download)

        if data:
            return data
    except Exception as exception:
        logger.debug(exception)
        raise AudioProviderError(f"YT-DLP download error - {url}") from exception

    raise AudioProviderError(f"No metadata found for the provided url {url}")

get_results(search_term, **kwargs) ¤

Get results from audio provider.

Arguments¤
  • search_term: The search term to use.
  • kwargs: Additional arguments.
Returns¤
  • A list of results.
Source code in spotdl/providers/audio/base.py
120
121
122
123
124
125
126
127
128
129
130
131
132
def get_results(self, search_term: str, **kwargs) -> List[Result]:
    """
    Get results from audio provider.

    ### Arguments
    - search_term: The search term to use.
    - kwargs: Additional arguments.

    ### Returns
    - A list of results.
    """

    raise NotImplementedError

get_views(url) ¤

Get the number of views for a video.

Arguments¤
  • url: The url of the video.
Returns¤
  • The number of views.
Source code in spotdl/providers/audio/base.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def get_views(self, url: str) -> int:
    """
    Get the number of views for a video.

    ### Arguments
    - url: The url of the video.

    ### Returns
    - The number of views.
    """

    data = self.get_download_metadata(url)

    return data["view_count"]

search(song, only_verified=False) ¤

Search for a song and return best match.

Arguments¤
  • song: The song to search for.
Returns¤
  • The url of the best match or None if no match was found.
Source code in spotdl/providers/audio/base.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
def search(self, song: Song, only_verified: bool = False) -> Optional[str]:
    """
    Search for a song and return best match.

    ### Arguments
    - song: The song to search for.

    ### Returns
    - The url of the best match or None if no match was found.
    """

    # Create initial search query
    search_query = create_song_title(song.name, song.artists).lower()
    if self.search_query:
        search_query = create_search_query(
            song, self.search_query, False, None, True
        )

    logger.debug("[%s] Searching for %s", song.song_id, search_query)

    isrc_urls: List[str] = []

    # search for song using isrc if it's available
    if song.isrc and self.SUPPORTS_ISRC and not self.search_query:
        isrc_results = self.get_results(song.isrc, **self.GET_RESULTS_OPTS[0])

        if only_verified:
            isrc_results = [result for result in isrc_results if result.verified]

        isrc_urls = [result.url for result in isrc_results]
        sorted_isrc_results = order_results(isrc_results, song, self.search_query)
        logger.debug(
            "[%s] Found %s results for ISRC %s",
            song.song_id,
            len(isrc_results),
            song.isrc,
        )

        if len(isrc_results) > 0:
            # get the best result, if the score is above 80 return it
            best_isrc_results = sorted(
                sorted_isrc_results.items(), key=lambda x: x[1], reverse=True
            )
            logger.debug(
                "[%s] Filtered to %s ISRC results",
                song.song_id,
                len(best_isrc_results),
            )

            if len(best_isrc_results) > 0:
                best_isrc = best_isrc_results[0]
                if best_isrc[1] > 80.0:
                    logger.debug(
                        "[%s] Best ISRC result is %s with score %s",
                        song.song_id,
                        best_isrc[0].url,
                        best_isrc[1],
                    )

                    return best_isrc[0].url

    results: Dict[Result, float] = {}
    for options in self.GET_RESULTS_OPTS:
        # Query YTM by songs only first, this way if we get correct result on the first try
        # we don't have to make another request
        search_results = self.get_results(search_query, **options)

        if only_verified:
            search_results = [
                result for result in search_results if result.verified
            ]

        logger.debug(
            "[%s] Found %s results for search query %s with options %s",
            song.song_id,
            len(search_results),
            search_query,
            options,
        )

        # Check if any of the search results is in the
        # first isrc results, since they are not hashable we have to check
        # by name
        isrc_result = next(
            (result for result in search_results if result.url in isrc_urls),
            None,
        )

        if isrc_result:
            logger.debug(
                "[%s] Best ISRC result is %s", song.song_id, isrc_result.url
            )

            return isrc_result.url

        logger.debug(
            "[%s] Have to filter results: %s", song.song_id, self.filter_results
        )

        if self.filter_results:
            # Order results
            new_results = order_results(search_results, song, self.search_query)
        else:
            new_results = {}
            if len(search_results) > 0:
                new_results = {search_results[0]: 100.0}

        logger.debug("[%s] Filtered to %s results", song.song_id, len(new_results))

        # song type results are always more accurate than video type,
        # so if we get score of 80 or above
        # we are almost 100% sure that this is the correct link
        if len(new_results) != 0:
            # get the result with highest score
            best_result, best_score = self.get_best_result(new_results)
            logger.debug(
                "[%s] Best result is %s with score %s",
                song.song_id,
                best_result.url,
                best_score,
            )

            if best_score >= 80 and best_result.verified:
                logger.debug(
                    "[%s] Returning verified best result %s with score %s",
                    song.song_id,
                    best_result.url,
                    best_score,
                )

                return best_result.url

            # Update final results with new results
            results.update(new_results)

    # No matches found
    if not results:
        logger.debug("[%s] No results found", song.song_id)
        return None

    # get the result with highest score
    best_result, best_score = self.get_best_result(results)
    logger.debug(
        "[%s] Returning best result %s with score %s",
        song.song_id,
        best_result.url,
        best_score,
    )

    return best_result.url

AudioProviderError ¤

Bases: Exception

Base class for all exceptions related to audio searching/downloading.

BandCamp(output_format='mp3', cookie_file=None, search_query=None, filter_results=True, yt_dlp_args=None) ¤

Bases: AudioProvider

SoundCloud audio provider class

Arguments¤
  • output_directory: The directory to save the downloaded songs to.
  • output_format: The format to save the downloaded songs in.
  • cookie_file: The path to a file containing cookies to be used by YTDL.
  • search_query: The query to use when searching for songs.
  • filter_results: Whether to filter results.
Source code in spotdl/providers/audio/base.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def __init__(
    self,
    output_format: str = "mp3",
    cookie_file: Optional[str] = None,
    search_query: Optional[str] = None,
    filter_results: bool = True,
    yt_dlp_args: Optional[str] = None,
) -> None:
    """
    Base class for audio providers.

    ### Arguments
    - output_directory: The directory to save the downloaded songs to.
    - output_format: The format to save the downloaded songs in.
    - cookie_file: The path to a file containing cookies to be used by YTDL.
    - search_query: The query to use when searching for songs.
    - filter_results: Whether to filter results.
    """

    self.output_format = output_format
    self.cookie_file = cookie_file
    self.search_query = search_query
    self.filter_results = filter_results

    if self.output_format == "m4a":
        ytdl_format = "bestaudio[ext=m4a]/bestaudio/best"
    elif self.output_format == "opus":
        ytdl_format = "bestaudio[ext=webm]/bestaudio/best"
    else:
        ytdl_format = "bestaudio"

    yt_dlp_options = {
        "format": ytdl_format,
        "quiet": True,
        "no_warnings": True,
        "encoding": "UTF-8",
        "logger": YTDLLogger(),
        "cookiefile": self.cookie_file,
        "outtmpl": f"{get_temp_path()}/%(id)s.%(ext)s",
        "retries": 5,
    }

    if yt_dlp_args:
        user_options = args_to_ytdlp_options(shlex.split(yt_dlp_args))
        yt_dlp_options.update(user_options)

    self.audio_handler = YoutubeDL(yt_dlp_options)

get_results(search_term, *_args, **_kwargs) ¤

Get results from slider.kz

Arguments¤
  • search_term: The search term to search for.
  • args: Unused.
  • kwargs: Unused.
Returns¤
  • A list of slider.kz results if found, None otherwise.
Source code in spotdl/providers/audio/bandcamp.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def get_results(self, search_term: str, *_args, **_kwargs) -> List[Result]:
    """
    Get results from slider.kz

    ### Arguments
    - search_term: The search term to search for.
    - args: Unused.
    - kwargs: Unused.

    ### Returns
    - A list of slider.kz results if found, None otherwise.
    """

    try:
        results = search(search_term)
    except KeyError:
        return []
    except Exception as exc:
        logger.error("Failed to get results from BandCamp", exc_info=exc)
        return []

    simplified_results: List[Result] = []
    for result in results:
        track = BandCampTrack(int(result[0]), int(result[1]))

        simplified_results.append(
            Result(
                source="bandcamp",
                url=track.track_url,
                verified=False,
                name=track.track_title,
                duration=track.track_duration_seconds,
                author=track.artist_title,
                result_id=track.track_url,
                search_query=search_term,
                album=track.album_title,
                artists=tuple(track.artist_title.split(", ")),
            )
        )

    return simplified_results

Piped(output_format='mp3', cookie_file=None, search_query=None, filter_results=True, yt_dlp_args=None) ¤

Bases: AudioProvider

YouTube Music audio provider class

Arguments¤
  • output_directory: The directory to save the downloaded songs to.
  • output_format: The format to save the downloaded songs in.
  • cookie_file: The path to a file containing cookies to be used by YTDL.
  • search_query: The query to use when searching for songs.
  • filter_results: Whether to filter results.
Source code in spotdl/providers/audio/piped.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def __init__(  # pylint: disable=super-init-not-called
    self,
    output_format: str = "mp3",
    cookie_file: Optional[str] = None,
    search_query: Optional[str] = None,
    filter_results: bool = True,
    yt_dlp_args: Optional[str] = None,
) -> None:
    """
    Pipe audio provider class

    ### Arguments
    - output_directory: The directory to save the downloaded songs to.
    - output_format: The format to save the downloaded songs in.
    - cookie_file: The path to a file containing cookies to be used by YTDL.
    - search_query: The query to use when searching for songs.
    - filter_results: Whether to filter results.
    """

    self.output_format = output_format
    self.cookie_file = cookie_file
    self.search_query = search_query
    self.filter_results = filter_results

    if self.output_format == "m4a":
        ytdl_format = "best[ext=m4a]/best"
    elif self.output_format == "opus":
        ytdl_format = "best[ext=webm]/best"
    else:
        ytdl_format = "best"

    yt_dlp_options = {
        "format": ytdl_format,
        "quiet": True,
        "no_warnings": True,
        "encoding": "UTF-8",
        "logger": YTDLLogger(),
        "cookiefile": self.cookie_file,
        "outtmpl": f"{get_temp_path()}/%(id)s.%(ext)s",
        "retries": 5,
    }

    if yt_dlp_args:
        user_options = args_to_ytdlp_options(shlex.split(yt_dlp_args))
        yt_dlp_options.update(user_options)

    self.audio_handler = YoutubeDL(yt_dlp_options)
    self.session = requests.Session()

get_download_metadata(url, download=False) ¤

Get metadata for a download using yt-dlp.

Arguments¤
  • url: The url to get metadata for.
Returns¤
  • A dictionary containing the metadata.
Source code in spotdl/providers/audio/piped.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
def get_download_metadata(self, url: str, download: bool = False) -> Dict:
    """
    Get metadata for a download using yt-dlp.

    ### Arguments
    - url: The url to get metadata for.

    ### Returns
    - A dictionary containing the metadata.
    """

    url_id = url.split("?v=")[1]
    piped_data = requests.get(
        f"https://pipedapi.kavin.rocks/streams/{url_id}",
        timeout=10,
        proxies=GlobalConfig.get_parameter("proxies"),
    ).json()

    yt_dlp_json = {
        "title": piped_data["title"],
        "id": url_id,
        "view_count": piped_data["views"],
        "extractor": "Generic",
        "formats": [],
    }

    for audio_stream in piped_data["audioStreams"]:
        yt_dlp_json["formats"].append(
            {
                "url": audio_stream["url"],
                "ext": "webm" if audio_stream["codec"] == "opus" else "m4a",
                "abr": audio_stream["quality"].split(" ")[0],
                "filesize": audio_stream["contentLength"],
            }
        )

    return self.audio_handler.process_video_result(yt_dlp_json, download=download)

get_results(search_term, **kwargs) ¤

Get results from YouTube Music API and simplify them

Arguments¤
  • search_term: The search term to search for.
  • kwargs: other keyword arguments passed to the YTMusic.search method.
Returns¤
  • A list of simplified results (dicts)
Source code in spotdl/providers/audio/piped.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def get_results(self, search_term: str, **kwargs) -> List[Result]:
    """
    Get results from YouTube Music API and simplify them

    ### Arguments
    - search_term: The search term to search for.
    - kwargs: other keyword arguments passed to the `YTMusic.search` method.

    ### Returns
    - A list of simplified results (dicts)
    """

    if kwargs is None:
        kwargs = {}

    params = {"q": search_term, **kwargs}

    response = self.session.get(
        "https://pipedapi.kavin.rocks/search",
        params=params,
        headers=HEADERS,
        timeout=20,
    )

    search_results = response.json()

    # Simplify results
    results = []
    for result in search_results["items"]:
        isrc_result = ISRC_REGEX.search(search_term)

        results.append(
            Result(
                source="piped",
                url=f"https://piped.video{result['url']}",
                verified=kwargs.get("filter") == "music_songs",
                name=result["title"],
                duration=result["duration"],
                author=result["uploaderName"],
                result_id=result["url"].split("?v=")[1],
                artists=(
                    (result["uploaderName"],)
                    if kwargs.get("filter") == "music_songs"
                    else None
                ),
                isrc_search=isrc_result is not None,
                search_query=search_term,
            )
        )

    return results

SliderKZ(output_format='mp3', cookie_file=None, search_query=None, filter_results=True, yt_dlp_args=None) ¤

Bases: AudioProvider

Slider.kz audio provider class

Arguments¤
  • output_directory: The directory to save the downloaded songs to.
  • output_format: The format to save the downloaded songs in.
  • cookie_file: The path to a file containing cookies to be used by YTDL.
  • search_query: The query to use when searching for songs.
  • filter_results: Whether to filter results.
Source code in spotdl/providers/audio/base.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def __init__(
    self,
    output_format: str = "mp3",
    cookie_file: Optional[str] = None,
    search_query: Optional[str] = None,
    filter_results: bool = True,
    yt_dlp_args: Optional[str] = None,
) -> None:
    """
    Base class for audio providers.

    ### Arguments
    - output_directory: The directory to save the downloaded songs to.
    - output_format: The format to save the downloaded songs in.
    - cookie_file: The path to a file containing cookies to be used by YTDL.
    - search_query: The query to use when searching for songs.
    - filter_results: Whether to filter results.
    """

    self.output_format = output_format
    self.cookie_file = cookie_file
    self.search_query = search_query
    self.filter_results = filter_results

    if self.output_format == "m4a":
        ytdl_format = "bestaudio[ext=m4a]/bestaudio/best"
    elif self.output_format == "opus":
        ytdl_format = "bestaudio[ext=webm]/bestaudio/best"
    else:
        ytdl_format = "bestaudio"

    yt_dlp_options = {
        "format": ytdl_format,
        "quiet": True,
        "no_warnings": True,
        "encoding": "UTF-8",
        "logger": YTDLLogger(),
        "cookiefile": self.cookie_file,
        "outtmpl": f"{get_temp_path()}/%(id)s.%(ext)s",
        "retries": 5,
    }

    if yt_dlp_args:
        user_options = args_to_ytdlp_options(shlex.split(yt_dlp_args))
        yt_dlp_options.update(user_options)

    self.audio_handler = YoutubeDL(yt_dlp_options)

get_results(search_term, *_args, **_kwargs) ¤

Get results from slider.kz

Arguments¤
  • search_term: The search term to search for.
  • args: Unused.
  • kwargs: Unused.
Returns¤
  • A list of slider.kz results if found, None otherwise.
Source code in spotdl/providers/audio/sliderkz.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def get_results(self, search_term: str, *_args, **_kwargs) -> List[Result]:
    """
    Get results from slider.kz

    ### Arguments
    - search_term: The search term to search for.
    - args: Unused.
    - kwargs: Unused.

    ### Returns
    - A list of slider.kz results if found, None otherwise.
    """

    search_results = None
    max_retries = 0

    while not search_results and max_retries < 3:
        try:
            search_response = requests.get(
                url="https://slider.kz/vk_auth.php?q=" + search_term,
                headers=HEADERS,
                timeout=5,
                proxies=GlobalConfig.get_parameter("proxies"),
            )

            # Check if the response is valid
            if len(search_response.text) > 30:
                # Set the search results to the json response
                # effectively breaking out of the loop
                search_results = search_response.json()

        except Exception as exc:
            logger.debug(
                "Slider.kz search failed for query %s with error: %s. Retrying...",
                search_term,
                exc,
            )

        max_retries += 1

    if not search_results:
        logger.debug("Slider.kz search failed for query %s", search_term)
        return []

    results = []
    for result in search_results["audios"][""]:
        # urls from slider.kz sometimes are relative, so we need to add the domain
        if "https://" not in result["url"]:
            result["url"] = "https://slider.kz/" + result["url"]

        results.append(
            Result(
                source="slider.kz",
                url=result.get("url"),
                verified=False,
                name=result.get("tit_art"),
                duration=int(result.get("duration", -9999)),
                author="slider.kz",
                result_id=result.get("id"),
                views=1,
            )
        )

    return results

SoundCloud(*args, **kwargs) ¤

Bases: AudioProvider

SoundCloud audio provider class

Arguments¤
  • args: Arguments passed to the AudioProvider class.
  • kwargs: Keyword arguments passed to the AudioProvider class.
Source code in spotdl/providers/audio/soundcloud.py
28
29
30
31
32
33
34
35
36
37
38
def __init__(self, *args: Any, **kwargs: Any) -> None:
    """
    Initialize the SoundCloud API

    ### Arguments
    - args: Arguments passed to the `AudioProvider` class.
    - kwargs: Keyword arguments passed to the `AudioProvider` class.
    """

    super().__init__(*args, **kwargs)
    self.client = SoundCloudClient()

get_results(search_term, *_args, **_kwargs) ¤

Get results from slider.kz

Arguments¤
  • search_term: The search term to search for.
  • args: Unused.
  • kwargs: Unused.
Returns¤
  • A list of slider.kz results if found, None otherwise.
Source code in spotdl/providers/audio/soundcloud.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def get_results(self, search_term: str, *_args, **_kwargs) -> List[Result]:
    """
    Get results from slider.kz

    ### Arguments
    - search_term: The search term to search for.
    - args: Unused.
    - kwargs: Unused.

    ### Returns
    - A list of slider.kz results if found, None otherwise.
    """

    results = list(islice(self.client.search(search_term), 20))
    regex = r"^(.+?)-|(\(\w+[\s\S]*\))"
    # Because anyone can post on soundcloud, we do another search with an edited search
    # The regex removes anything in brackets and the artist(s)'s name(s) if in the name
    edited_search_term = re.sub(regex, "", search_term)
    results.extend(list(islice(self.client.search(edited_search_term), 20)))

    # Simplify results
    simplified_results = []
    for result in results:
        if result.kind != "track":
            continue

        # Ignore results that are not playable
        if "/preview/" in result.media.transcodings[0].url:
            continue

        album = self.client.get_track_albums(result.id)

        try:
            album_name = next(album).title
        except StopIteration:
            album_name = None

        simplified_results.append(
            Result(
                source="soundcloud",
                url=result.permalink_url,
                name=result.title,
                verified=result.user.verified,
                duration=result.full_duration,
                author=result.user.username,
                result_id=result.id,
                isrc_search=False,
                search_query=search_term,
                views=result.playback_count,
                explicit=False,
                album=album_name,
            )
        )

    return simplified_results

YTDLLogger ¤

Custom YT-dlp logger.

debug(msg) ¤

YTDL uses this to print debug messages.

Source code in spotdl/providers/audio/base.py
38
39
40
41
42
43
def debug(self, msg):
    """
    YTDL uses this to print debug messages.
    """

    pass  # pylint: disable=W0107

error(msg) ¤

YTDL uses this to print errors.

Source code in spotdl/providers/audio/base.py
52
53
54
55
56
57
def error(self, msg):
    """
    YTDL uses this to print errors.
    """

    raise AudioProviderError(msg)

warning(msg) ¤

YTDL uses this to print warnings.

Source code in spotdl/providers/audio/base.py
45
46
47
48
49
50
def warning(self, msg):
    """
    YTDL uses this to print warnings.
    """

    pass  # pylint: disable=W0107

YouTube(output_format='mp3', cookie_file=None, search_query=None, filter_results=True, yt_dlp_args=None) ¤

Bases: AudioProvider

YouTube audio provider class

Arguments¤
  • output_directory: The directory to save the downloaded songs to.
  • output_format: The format to save the downloaded songs in.
  • cookie_file: The path to a file containing cookies to be used by YTDL.
  • search_query: The query to use when searching for songs.
  • filter_results: Whether to filter results.
Source code in spotdl/providers/audio/base.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def __init__(
    self,
    output_format: str = "mp3",
    cookie_file: Optional[str] = None,
    search_query: Optional[str] = None,
    filter_results: bool = True,
    yt_dlp_args: Optional[str] = None,
) -> None:
    """
    Base class for audio providers.

    ### Arguments
    - output_directory: The directory to save the downloaded songs to.
    - output_format: The format to save the downloaded songs in.
    - cookie_file: The path to a file containing cookies to be used by YTDL.
    - search_query: The query to use when searching for songs.
    - filter_results: Whether to filter results.
    """

    self.output_format = output_format
    self.cookie_file = cookie_file
    self.search_query = search_query
    self.filter_results = filter_results

    if self.output_format == "m4a":
        ytdl_format = "bestaudio[ext=m4a]/bestaudio/best"
    elif self.output_format == "opus":
        ytdl_format = "bestaudio[ext=webm]/bestaudio/best"
    else:
        ytdl_format = "bestaudio"

    yt_dlp_options = {
        "format": ytdl_format,
        "quiet": True,
        "no_warnings": True,
        "encoding": "UTF-8",
        "logger": YTDLLogger(),
        "cookiefile": self.cookie_file,
        "outtmpl": f"{get_temp_path()}/%(id)s.%(ext)s",
        "retries": 5,
    }

    if yt_dlp_args:
        user_options = args_to_ytdlp_options(shlex.split(yt_dlp_args))
        yt_dlp_options.update(user_options)

    self.audio_handler = YoutubeDL(yt_dlp_options)

get_results(search_term, *_args, **_kwargs) ¤

Get results from YouTube

Arguments¤
  • search_term: The search term to search for.
  • args: Unused.
  • kwargs: Unused.
Returns¤
  • A list of YouTube results if found, None otherwise.
Source code in spotdl/providers/audio/youtube.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def get_results(
    self, search_term: str, *_args, **_kwargs
) -> List[Result]:  # pylint: disable=W0221
    """
    Get results from YouTube

    ### Arguments
    - search_term: The search term to search for.
    - args: Unused.
    - kwargs: Unused.

    ### Returns
    - A list of YouTube results if found, None otherwise.
    """

    search_results: Optional[List[PyTube]] = Search(search_term).results

    if not search_results:
        return []

    results = []
    for result in search_results:
        if result.watch_url:
            try:
                duration = result.length
            except Exception:
                duration = 0

            try:
                views = result.views
            except Exception:
                views = 0

            results.append(
                Result(
                    source=self.name,
                    url=result.watch_url,
                    verified=False,
                    name=result.title,
                    duration=duration,
                    author=result.author,
                    search_query=search_term,
                    views=views,
                    result_id=result.video_id,
                )
            )

    return results

YouTubeMusic(*args, **kwargs) ¤

Bases: AudioProvider

YouTube Music audio provider class

Arguments¤
  • args: Arguments passed to the AudioProvider class.
  • kwargs: Keyword arguments passed to the AudioProvider class.
Source code in spotdl/providers/audio/ytmusic.py
27
28
29
30
31
32
33
34
35
36
37
38
def __init__(self, *args: Any, **kwargs: Any) -> None:
    """
    Initialize the YouTube Music API

    ### Arguments
    - args: Arguments passed to the `AudioProvider` class.
    - kwargs: Keyword arguments passed to the `AudioProvider` class.
    """

    super().__init__(*args, **kwargs)

    self.client = YTMusic(language="de")

get_results(search_term, **kwargs) ¤

Get results from YouTube Music API and simplify them

Arguments¤
  • search_term: The search term to search for.
  • kwargs: other keyword arguments passed to the YTMusic.search method.
Returns¤
  • A list of simplified results (dicts)
Source code in spotdl/providers/audio/ytmusic.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def get_results(self, search_term: str, **kwargs) -> List[Result]:
    """
    Get results from YouTube Music API and simplify them

    ### Arguments
    - search_term: The search term to search for.
    - kwargs: other keyword arguments passed to the `YTMusic.search` method.

    ### Returns
    - A list of simplified results (dicts)
    """

    search_results = self.client.search(search_term, **kwargs)

    # Simplify results
    results = []
    for result in search_results:
        if (
            result is None
            or result.get("videoId") is None
            or result.get("artists") in [[], None]
        ):
            continue

        isrc_result = ISRC_REGEX.search(search_term)

        results.append(
            Result(
                source=self.name,
                url=(
                    f'https://{"music" if result["resultType"] == "song" else "www"}'
                    f".youtube.com/watch?v={result['videoId']}"
                ),
                verified=result.get("resultType") == "song",
                name=result["title"],
                result_id=result["videoId"],
                author=result["artists"][0]["name"],
                artists=tuple(map(lambda a: a["name"], result["artists"])),
                duration=parse_duration(result.get("duration")),
                isrc_search=isrc_result is not None,
                search_query=search_term,
                explicit=result.get("isExplicit"),
                album=(
                    result.get("album", {}).get("name")
                    if result.get("album")
                    else None
                ),
            )
        )

    return results