Scrobble your vinyl to Last.fm with a Raspberry Pi
A small Python program for a Raspberry Pi next to a turntable: it records ten seconds with arecord, identifies the song with AudD, shows it, and scrobbles it to Last.fm, sending a clip only when there is sound and the song isn't known yet.
You can use a Raspberry Pi to scrobble the records you play to Last.fm. We wanted to make it as simple as possible: the Raspberry Pi records ten seconds of audio, we send you the song, and a small Python program scrobbles it to Last.fm. To save requests, it only sends the clips with music in them, and only when it doesn’t know the song yet.
Now playing: Tears For Fears - Everybody Wants To Rule The World
Scrobbling: Tears For Fears - Everybody Wants To Rule The World
Silence: the record has stopped or the side has ended
What you need
- A Raspberry Pi with Raspberry Pi OS, connected to your network. The program requires Python 3.10 or later.
- A USB audio interface with a line input, or a USB microphone.
- You can get a token from our API Dashboard. New accounts get a free trial of 300 requests, usable for 14 days, where available, with no credit card.
- A Last.fm account. You’ll create an API account for the program in Step 3.
Connect the turntable
The output of a turntable is usually at such a low level that it is necessary for the signal to be amplified. Some turntables do it themselves: if yours has a PHONO/LINE switch on the back, set it to LINE and connect the turntable to the line input. Otherwise, connect it to a phono preamp first, or to a USB interface with a phono input, like the Behringer UFO202 (its switch is to “select PHONO for a record player or LINE for other sources”).
Please don’t connect the turntable to a line input while the switch is set to PHONO. You can also use a USB microphone: put it close to a speaker.
Step 1: Record a clip with arecord
To list the sound cards, run the following command:
arecord -l
Find your USB interface in the list and note the card number and the device number. Then put on a record and record ten seconds:
mkdir -p ~/scrobbler && cd ~/scrobbler
arecord -D plughw:1,0 -d 10 -f cd -t wav test.wav
The numbers after plughw: stand for the sound card number and the device number: in the list, the line card 1: ..., device 0: ... is plughw:1,0. -f cd asks for 16-bit stereo at 44,100 Hz, and plughw converts the rate, the format and the channels if the interface records in another one. Ten seconds is enough: the standard endpoint analyzes up to the first 12 seconds of audio. The standard endpoint accepts files up to 10 MB, and ten seconds of CD-quality WAV is about 1.8 MB.
Step 2: Identify the clip
From Raspberry Pi OS Bookworm onwards, you cannot install libraries directly into the system version of Python, so create a virtual environment and install the SDK there:
cd ~/scrobbler
python3 -m venv venv
venv/bin/pip install audd
To test the recognition, create a file called first.py with the following code:
from audd import AudD
audd = AudD("your-api-token") # get your own token at dashboard.audd.io
song = audd.recognize("test.wav")
if song:
print(song.artist, "-", song.title)
else:
print("No match: play the record a little louder and try again")
Run it with venv/bin/python first.py. You should see the artist and the title of the song. If the server has successfully processed the request, but there are no matches, recognize() returns None. If that happens while the music plays, Step 6 shows how loud your clips are.
Without code. The AudD CLI records from the same device and identifies the song:
audd listen --device plughw:1,0. It records 10 seconds with ffmpeg, or with sox when ffmpeg is not installed, and deletes the recording afterwards. To record, it needs ffmpeg or sox: you can install ffmpeg withsudo apt install ffmpeg. Install the CLI withcurl -fsSL https://github.com/AudDMusic/audd-cli/releases/latest/download/install.sh | sh(it has builds for the 64-bit Raspberry Pi OS). Over SSH,audd loginprints a page and a code: open the page on any device and approve.
Step 3: Create a Last.fm API account
You’ll need a Last.fm API account for the program. Log in to Last.fm and create one, then copy the API key and the shared secret for Step 4. For security reasons, keep the shared secret private: anyone who has it can sign requests as your program.
The program signs in the same way as desktop applications. It gets a token from Last.fm, and you open a page on Last.fm to allow access. After that, the program exchanges the token for a session key. Session keys have an infinite lifetime by default, so you only need to do this once.
Step 4: The program
Create a file called scrobbler.env in ~/scrobbler with your tokens and the device:
AUDD_API_TOKEN=your-api-token
LASTFM_API_KEY=your-lastfm-api-key
LASTFM_API_SECRET=your-lastfm-shared-secret
ALSA_DEVICE=plughw:1,0
Then create a file called scrobbler.py with the following code:
"""Listen to a turntable, show what's playing, and scrobble it to Last.fm."""
import hashlib
import io
import json
import math
import os
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import wave
from array import array
from pathlib import Path
from audd import AudD, AudDAuthenticationError, AudDError, AudDQuotaError
DEVICE = os.environ.get("ALSA_DEVICE", "plughw:1,0") # card 1, device 0 in `arecord -l`
CLIP_SECONDS = 10 # the standard endpoint analyzes up to the first 12 seconds
QUIET_LEVEL = 300 # a clip below this level counts as silence: see "Set the silence level"
NO_MATCH_PAUSE = 30 # seconds to wait after a clip that didn't match
RECHECK_SECONDS = 60 # how often to check a song whose length is unknown
LASTFM_API = "https://ws.audioscrobbler.com/2.0/"
HERE = Path(__file__).resolve().parent
SESSION_FILE = HERE / "lastfm-session.txt"
PENDING_FILE = HERE / "pending-scrobbles.json"
def lastfm(method, **params):
"""Sign a Last.fm API call, POST it and return the decoded JSON."""
params = {"method": method, "api_key": os.environ["LASTFM_API_KEY"], **params}
signature = "".join(name + str(params[name]) for name in sorted(params))
signature += os.environ["LASTFM_API_SECRET"]
params["api_sig"] = hashlib.md5(signature.encode("utf-8")).hexdigest()
params["format"] = "json" # format is not part of the signature
body = urllib.parse.urlencode(params).encode("utf-8")
try:
with urllib.request.urlopen(LASTFM_API, data=body, timeout=30) as resp:
return json.load(resp)
except urllib.error.HTTPError as err:
return json.load(err) # Last.fm sends the error code in the body
def login():
"""Authorize this program on your Last.fm account and save the session key."""
token = lastfm("auth.getToken")["token"]
print("Open this page, allow access, then come back and press Enter:")
print(f"https://www.last.fm/api/auth/?api_key={os.environ['LASTFM_API_KEY']}&token={token}")
input()
reply = lastfm("auth.getSession", token=token)
if "error" in reply:
sys.exit(f"Last.fm error {reply['error']}: {reply['message']}")
SESSION_FILE.write_text(reply["session"]["key"])
print("Signed in to Last.fm as", reply["session"]["name"])
def session_key():
if not SESSION_FILE.exists():
sys.exit("No Last.fm session: run `python scrobbler.py login` first")
return SESSION_FILE.read_text().strip()
def track_params(play):
params = {"artist": play["artist"], "track": play["title"]}
if play["album"]:
params["album"] = play["album"]
if play["length"]:
params["duration"] = round(play["length"])
return params
def now_playing(play):
"""Show the song on your Last.fm profile. Failures are not retried."""
try:
reply = lastfm("track.updateNowPlaying", sk=session_key(), **track_params(play))
except (OSError, ValueError) as err:
reply = {"error": "-", "message": str(err)}
if "error" in reply:
print("Last.fm now playing failed:", reply["message"])
def scrobble(play):
"""Queue a scrobble, then send the queue to Last.fm, oldest first."""
pending = json.loads(PENDING_FILE.read_text()) if PENDING_FILE.exists() else []
pending.append({**track_params(play), "timestamp": play["started"]})
while pending:
batch = pending[:50] # Last.fm takes up to 50 scrobbles per request
params = {f"{name}[{i}]": value
for i, item in enumerate(batch) for name, value in item.items()}
try:
reply = lastfm("track.scrobble", sk=session_key(), **params)
except (OSError, ValueError) as err:
print("Last.fm unreachable, will retry:", err)
break
error = reply.get("error")
if error in (11, 16):
print("Last.fm is busy, will retry:", reply["message"])
break
if error == 9:
print("The Last.fm session is no longer valid: run `python scrobbler.py login`")
break
if error:
print(f"Last.fm rejected {len(batch)} scrobble(s): {reply['message']}")
del pending[:50]
PENDING_FILE.write_text(json.dumps(pending))
def maybe_scrobble(play):
"""Scrobble a play once it meets Last.fm's rules, and only once."""
if play["scrobbled"]:
return
length = play["length"]
if length is not None and length <= 30:
return # the track must be longer than 30 seconds
needed = min(length / 2, 240) if length else 240 # half the track, or 4 minutes
if play["heard_until"] - play["started"] >= needed:
play["scrobbled"] = True
print(f"Scrobbling: {play['artist']} - {play['title']}")
scrobble(play)
def record():
"""Record one clip; return the WAV bytes and the clip's level."""
proc = subprocess.run(
["arecord", "-q", "-D", DEVICE, "-d", str(CLIP_SECONDS), "-f", "cd", "-t", "wav"],
capture_output=True,
)
if proc.returncode != 0:
sys.exit("arecord failed: " + proc.stderr.decode(errors="replace").strip())
with wave.open(io.BytesIO(proc.stdout)) as clip:
samples = array("h", clip.readframes(clip.getnframes()))[::10]
level = math.sqrt(sum(s * s for s in samples) / len(samples)) if samples else 0
return proc.stdout, level
def seconds(timecode):
"""'01:25' -> 85"""
total = 0
for part in (timecode or "").split(":"):
if not part.isdigit():
return None
total = total * 60 + int(part)
return total
def levels():
"""Print the level of each clip. Sends nothing to AudD."""
while True:
_, level = record()
print(f"level {level:.0f}")
def run():
audd = AudD() # reads AUDD_API_TOKEN; get your own token at dashboard.audd.io
session_key() # stop now if `login` hasn't been run
play = None # the song on the turntable, once AudD has named it
next_check = 0 # don't send a clip to AudD before this time
while True:
clip_start = time.time()
wav, level = record()
now = time.time()
if level < QUIET_LEVEL:
if play:
print("Silence: the record has stopped or the side has ended")
play, next_check = None, 0
continue
if now < next_check:
if play and play["playing"]:
play["heard_until"] = now # the song AudD named is still playing
maybe_scrobble(play)
continue
try:
song = audd.recognize(wav, return_metadata="spotify")
except (AudDAuthenticationError, AudDQuotaError):
raise # a problem with the token or the plan: stop and show it
except AudDError as err:
print("AudD request failed:", err)
next_check = now + NO_MATCH_PAUSE
continue
if song is None or not (song.artist and song.title):
print(f"No match (level {level:.0f})")
if play:
play["playing"] = False
next_check = now + NO_MATCH_PAUSE
continue
length = None
if song.spotify and song.spotify.duration_ms:
length = song.spotify.duration_ms / 1000
if play is None or (play["artist"], play["title"]) != (song.artist, song.title):
play = {"artist": song.artist, "title": song.title, "album": song.album,
"length": length, "started": int(clip_start), "scrobbled": False}
print(f"Now playing: {song.artist} - {song.title}")
now_playing(play)
play["playing"] = True
play["heard_until"] = now
maybe_scrobble(play)
position = seconds(song.timecode) # where in the song this clip was
if length and position is not None:
next_check = max(clip_start - position + length, now + CLIP_SECONDS)
else:
next_check = now + RECHECK_SECONDS
if __name__ == "__main__":
commands = {"login": login, "levels": levels, "run": run}
command = sys.argv[1] if len(sys.argv) > 1 else "run"
if command not in commands:
sys.exit("usage: python scrobbler.py [login | levels | run]")
commands[command]()
The program only needs the SDK and the standard library. It saves the session key to lastfm-session.txt and the scrobbles that haven’t been sent yet to pending-scrobbles.json.
Step 5: Sign in to Last.fm
Load the variables from scrobbler.env and run the login command:
cd ~/scrobbler
set -a; . ./scrobbler.env; set +a
venv/bin/python scrobbler.py login
The program prints an address on last.fm. Open it on any device, allow access, and press Enter in the terminal. The token in the address is valid for 60 minutes and can only be used once. If you remove the program’s access in your Last.fm settings, run the login command again.
Step 6: Set the silence level
Run the levels command to see the level of each clip (nothing is sent to our servers):
venv/bin/python scrobbler.py levels
Note the level when the record is stopped and when the music plays, then press Ctrl+C. Open scrobbler.py and set QUIET_LEVEL to a number between the two. Clips below the quiet level are never sent to the API. If the program is able to hear the room, you’ll see a higher level of silence.
Step 7: Run it
In the same terminal, start the program:
venv/bin/python scrobbler.py
Put on a record. When we recognize the first song, the program prints Now playing, and Last.fm shows the song on your profile as the one you’re listening to. When half of the song has played (or four minutes), the program prints Scrobbling, and the song is added to your profile.
How the program saves requests
The program records the audio from the turntable in 10-second clips. Every clip it sends to the standard endpoint counts as one request. If you don’t want every one of these clips to be recognized and counted as a request, there are three settings that you can use: QUIET_LEVEL, RECHECK_SECONDS and NO_MATCH_PAUSE.
Note that the program never sends the clips below QUIET_LEVEL, and it doesn’t send any clips while the song we recognized is playing. You can change how often it checks a song without a length (RECHECK_SECONDS, 60 seconds) and how long it waits after a clip that didn’t match (NO_MATCH_PAUSE, 30 seconds). So if you want it to check the song every 2 minutes instead of every minute, RECHECK_SECONDS should be 120.
After we recognize the song, the program stops sending clips until the song ends. To know when that is, it asks for the Spotify metadata (return_metadata="spotify"). The Spotify block has the length of the track, and the timecode is the time in the song when the clip you sent is played. So if the clip started at 20:00:00, the timecode is 01:30 and the track is 4 minutes long, the song ends at 20:02:30.
When the songs change without a gap
If you lift the needle and put it on another track, the program hears the silence and recognizes the next song. If the next song starts before the old one ends, without silence, the program recognizes it when the old one should have ended.
What it costs
Normally, our plans include as-you-go pricing: some number of requests is included with your monthly bill, but you can send requests on top of what’s included and will be charged for those separately. For example, if you listen to records for two hours a day, that’s about 30 songs a day. Here is what 30 days of that cost:
- This program, at 1 or 2 requests per song with a Spotify length: 900 to 1,800 requests a month, $5 to $9 on the Indie plan ($5 per month with 1,000 requests, then $5.00 per 1,000).
- A clip every 10 seconds of music: 21,600 requests, $5 + 20.6 × $5.00 = $108 on Indie.
- A clip every 10 seconds, 24 hours a day: 259,200 requests, $850 + 59.2 × $4.25 = $1,101.60 on the Pro plan ($850 per month with 200,000 requests, then $4.25 per 1,000).
The free trial’s 300 requests last 5 to 10 days of this listening. If you want a hard monthly cap on requests, email [email protected] and we’ll set one on your account. The prices are from our pricing page.
When a play counts as a scrobble
A track should only be scrobbled when it is longer than 30 seconds and has been played for at least half its duration, or for 4 minutes (whichever occurs earlier). As soon as these conditions have been met, the scrobble request may be sent at any time.
By default, the program will scrobble a song when half of it has played, or after 4 minutes. It counts the time from the first clip we recognized to the last clip with music. Note that without the Spotify block, the program won’t know the length of the track: it scrobbles the song after 4 minutes, and a song shorter than that is not scrobbled. A track of 30 seconds or less is never scrobbled.
Last.fm wants the time the track started playing, as a UNIX timestamp in UTC. The program sends the start of the first clip we recognized. Now Playing requests that fail should not be retried, so the program sends Now Playing once, when we recognize a new song, and doesn’t retry it.
Don’t scrobble the same track twice
You’ll only see one scrobble for every song you play. If we recognize the same song again, even after a clip that didn’t match, the program knows that it’s still the same play. When it hears silence, the play ends: if you lift the needle and play the track again, it’s a new play, and it will be scrobbled again.
When Last.fm is unreachable
If the program can’t connect to Last.fm, it puts the scrobbles in a queue, in pending-scrobbles.json. When Last.fm is back online, the program sends all of the backlog with the next scrobble, oldest first, up to 50 per request. Last.fm recommends this: the cache should survive client restarts, and cached scrobbles should be sent before new scrobbles.
There are 3 kinds of Last.fm errors: 11 and 16 (which mean that the service is temporarily unavailable), 9 (which means that the session key is invalid) and all other codes (which mean that the request was incorrectly formed in some way and should not be retried). The program keeps the scrobbles on 11, 16 and 9, and drops them on the other codes. If something happens to the session key, the program will let you know by printing a message so you can run the login command again.
Last.fm can also ignore a scrobble without an error, for example when the daily scrobble limit is exceeded.
When AudD returns an error
If the token is invalid or there are no requests left on your plan, the program stops with the error, and the service below starts it again after a minute. If something else happens (for example, the network is down), the program prints the error and tries again 30 seconds later. The SDK retries a request that failed before the clip was uploaded, but not one that timed out after: that request might still be counted. The error codes are in the errors reference.
Run it at boot with systemd
Create a file called /etc/systemd/system/scrobbler.service, with your user name instead of pi in the four places:
[Unit]
Description=Vinyl scrobbler
After=network-online.target
Wants=network-online.target
[Service]
User=pi
WorkingDirectory=/home/pi/scrobbler
EnvironmentFile=/home/pi/scrobbler/scrobbler.env
ExecStart=/home/pi/scrobbler/venv/bin/python -u scrobbler.py
Restart=on-failure
RestartSec=60
[Install]
WantedBy=multi-user.target
Run login first: the service can’t wait for you to press Enter. Then start the service, and start it at every boot:
sudo systemctl daemon-reload
sudo systemctl enable --now scrobbler
journalctl -u scrobbler -f
EnvironmentFile passes the variables from scrobbler.env to the program. With -u, Python prints each line right away, so you can follow the output with journalctl. Restart=on-failure restarts the program when it exits with an error, after RestartSec (60 seconds).
Related
Reading this as an AI agent? The raw Markdown is at recipes/vinyl-scrobbler-raspberry-pi.md, and the full index is /resources/llms.txt.
