Skip to content
Projets

À propos

🎵 Bibliothèque asynchrone gratuite basée sur l’API Shazam obtenue par rétro-ingénierie, écrite en Python 3.10 ou ultérieur avec asyncio et aiohttp.

Design et médias

Comment ces chiffres sont mesurés

Progression mesurée des étoiles

in 24h
0
in 7 days
+11
in 15 days
+19
in 1 month
Historique en cours

Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.

README.md

Original

PyPI version Downloads Downloads per month License

🎵 Is a FREE asynchronous library from reverse engineered Shazam API written in Python 3.11+ with asyncio and aiohttp. Recognizes a song from a file or from bytes, reads a track, and returns every chart Shazam publishes.


💿 Installation

💲 pip install shazamio

💻 Example

🔎🎵 Recognize track

Recognize a track from a file, a pathlib.Path, or the bytes of one. The sample below ships with the repository, in examples/data/. The signature covers 12 s of the audio, the window Shazam clients send; segment_duration_seconds still takes another one and warns, and from 15 s up Shazam finds nothing at all

import asyncio
from shazamio import Shazam


async def main():
    async with Shazam() as shazam:
        out = await shazam.recognize("Gloria.ogg")

        print(out.track.title)  # I Will Survive


asyncio.run(main())
🎵📄 About track

Get track information
https://www.shazam.com/track/552406075/ale-jazz

import asyncio
from shazamio import Shazam


async def main():
    async with Shazam() as shazam:
        track = await shazam.track_about(track_id=552406075)

        print(track.title, track.subtitle)


asyncio.run(main())
🎵📺 YouTube video of a track

The video Shazam shows for a track, looked up by its artist and title

import asyncio
from shazamio import Shazam


async def main():
    async with Shazam() as shazam:
        out = await shazam.recognize("Gloria.ogg")

        video = await shazam.get_youtube_data(link=out.track.youtube_link)
        print(video.uri)  # https://youtu.be/6dYWe1c3OyU?autoplay=1


asyncio.run(main())
🍎🔑 Apple Music ids to Shazam track keys

Resolve Apple Music track ids to the Shazam track keys track_about takes, in one request. A call with several ids keys every entry by the id Shazam stores, which can be one you never sent, so read the values instead of indexing by what you asked for. A call with a single id keys it by that id. Either way an id Shazam has no track for is absent, so the map can be shorter than the list you passed.

import asyncio
from shazamio import Shazam


async def main():
    async with Shazam() as shazam:
        keys = await shazam.track_keys_from_apple_ids([1125281672, 1440650711])

        print(keys)  # {'1125281672': '325127876', '6781023657': '56670613'}


asyncio.run(main())
🔎🎶 Search tracks by text, through Apple's index

Shazam no longer answers text search, so this searches Apple's iTunes index and fetches the Shazam track of every song found. Relevance and order are Apple's. Songs Shazam has no track for are left out and versions sharing one Shazam track come back once, so you can get fewer tracks than limit. Each song costs two requests, which is why limit defaults to 5.

import asyncio
from shazamio import Shazam


async def main():
    async with Shazam() as shazam:
        tracks = await shazam.search_tracks_via_itunes("daft punk one more time")

        print([track.title for track in tracks])
        # ['One More Time', 'One More Time (12 Mix)', "One More Time (Romanthony's Unplugged)"]


asyncio.run(main())
🔝🎶🌏 Top tracks in world

The 200 most shazamed tracks worldwide
https://www.shazam.com/charts/top-200/world

import asyncio
from shazamio import Shazam


async def main():
    async with Shazam() as shazam:
        tracks = await shazam.top_world_tracks(limit=10)

        for track in tracks:
            print(f"{track.rank}. {track.artist} - {track.title}")


asyncio.run(main())
🔝🎶🏳️ Top tracks in country

The 200 most shazamed tracks in a country
https://www.shazam.com/charts/top-200/netherlands

import asyncio
from shazamio import Shazam


async def main():
    async with Shazam() as shazam:
        tracks = await shazam.top_country_tracks(
            country_code="NL",
            limit=5,
        )

        for track in tracks:
            print(f"{track.rank}. {track.artist} - {track.title}")


asyncio.run(main())
🔝🎶🏙️ Top tracks in city

The 50 most shazamed tracks in a city. The city name is the one services/charts/locations publishes
https://www.shazam.com/charts/top-50/russia/moscow

import asyncio
from shazamio import Shazam


async def main():
    async with Shazam() as shazam:
        tracks = await shazam.top_city_tracks(
            country_code="RU",
            city_name="Moscow",
            limit=10,
        )

        for track in tracks:
            print(f"{track.rank}. {track.artist} - {track.title}")


asyncio.run(main())
🔝🎶🌏🎸 Top tracks in world by genre

The most shazamed tracks worldwide in one genre
https://www.shazam.com/charts/genre/world/rock

import asyncio
from shazamio import GenreMusic, Shazam


async def main():
    async with Shazam() as shazam:
        tracks = await shazam.top_world_genre_tracks(
            genre=GenreMusic.ROCK,
            limit=10,
        )

        for track in tracks:
            print(f"{track.rank}. {track.artist} - {track.title}")


asyncio.run(main())
🔝🎶🏳️🎸 Top tracks in country by genre

The most shazamed tracks in a country in one genre. Shazam offers only a handful of genres per country, and asking for one it does not offer answers 404, which surfaces as aiohttp.ClientResponseError
https://www.shazam.com/charts/genre/spain/hip-hop-rap

import asyncio
from shazamio import GenreMusic, Shazam


async def main():
    async with Shazam() as shazam:
        tracks = await shazam.top_country_genre_tracks(
            country_code="ES",
            genre=GenreMusic.HIP_HOP_RAP,
            limit=4,
        )

        for track in tracks:
            print(f"{track.rank}. {track.artist} - {track.title}")


asyncio.run(main())

🔌 Closing what you open

A Shazam opens one connection pool on its first request and reuses it for every later one, so ten calls no longer cost ten connections. The pool lives until you close it, which async with does for you:

async with Shazam() as shazam:
    ...

Without a close the pool stays open and aiohttp reports it when the object is collected: Unclosed client session. await shazam.close() does the same job where a block does not fit, and a request after either one raises RuntimeError: Session is closed.

A pool belongs to the event loop it was opened on. A Shazam kept across several asyncio.run calls opens a new pool on each new loop and abandons the old one, which aiohttp reports the same way. A closed Shazam stays closed in every loop. Prefer one asyncio.run around all the calls.

An HTTPClient you build yourself is yours to close: Shazam closes only the client it builds for itself. examples/recognize.py shows both blocks.

🎯 When a match may be wrong

Shazam sometimes answers with a confident match for the wrong track, and some recordings get one at every offset. recognize(..., max_skew=1e-3) turns an answer whose first match is skewed beyond the limit into a no-match, which removes most of those. It is off by default because it also rejects audio played faster, slower or pitch-shifted; the recognize docstring has the measurements.

📊 What the chart methods return

Shazam publishes its charts as CSV with three columns, so a chart entry is a ChartTrack carrying a rank, an artist and a title, and nothing else. A chart has no ids, no artwork and no provider links, so it is not a TrackInfo. Nothing in the library resolves a chart row to a track id either: Shazam retired the search endpoints that used to do it.

A row without exactly three fields is skipped and logged as a warning on the shazamio logger, so a chart can come back shorter than the one Shazam serves.

limit defaults to the whole chart, and offset skips entries from the top: both are applied to the chart the service returns, which is always the full one.

🔧 What the track methods return

recognize returns a ResponseTrack, track_about and search_tracks_via_itunes return TrackInfo objects, and get_youtube_data returns a YoutubeData. They used to return the raw dictionaries. A track carries the title, the artist, the artwork and the provider links. Top-level keys that no field reads, such as genres or isrc, stay on the model: read them as attributes (track.genres) or from track.model_extra. The images, hub and artists objects do not: the model keeps only the values its fields read from them (photo_url, apple_music_url, ringtone, providers, artist_id), so images.background or hub.explicit is gone. An answer that does not fit the model raises BadParseData.

Serialize.track, Serialize.full_track and Serialize.youtube build the same models from a stored payload. Code that still passes them a method's result keeps working, since a model passed in comes back unchanged.

Open photo: what song information looks like (Custom serializer)

Recognition request profiles

Recognition defaults to the iPhone route, as in 0.9.0. To diagnose differences between client profiles, select a fixed route explicitly:

from shazamio import Device, Shazam

async with Shazam(recognition_device=Device.ANDROID) as shazam:
    result = await shazam.recognize("audio.wav")

recognition_device accepts Device.IPHONE (the default), Device.ANDROID, or Device.WEB. Plain strings ("iphone", "android", or "web") also work at runtime; use the enum for type checking. Invalid values raise ValueError when constructing the client.

Only the recognition URL's device segment changes. All profiles retain the existing X-Shazam-Platform: IPHONE and X-Shazam-AppVersion: 14.1.0 headers, with a randomly selected Android Dalvik user agent. Other endpoints retain their existing routes and headers.

This option does not change fingerprints, retries, or rate limits, and does not rotate profiles automatically. A 429 still means the caller must back off. Changing profiles can change response fields: web responses may omit hub.providers, and Android responses may contain intent:// Apple Music links. Applications depending on those fields should retain the default until they have checked compatibility.

Explorer des projets similaires

Chargement…