This Python script is designed to automatically scrobble the tracks played on a Spinitron radio station to a user's Last.fm account. It uses the Flask web framework to create a simple web application that allows users to input the URL of a Spinitron radio station. The script then periodically checks the Spinitron page for the currently playing track and scrobbles it to Last.fm if it's a new track.
Here's how the script works:
- The script starts by importing the necessary libraries, including
threading
,time
,schedule
,pylast
,requests
,BeautifulSoup
, andFlask
. - The user's Last.fm API credentials (API key, API secret, and session key) are defined, and a Last.fm API client (
network
) is set up using thepylast
library. - The Flask web application is created with the
app
variable. - Two global variables,
last_scrobbled_track
andspinitron_url
, are defined to keep track of the most recently scrobbled track and the URL of the Spinitron radio station, respectively. - An event object (
stop_event
) is created to control the scheduler thread. - The
run_scheduler
function is defined to run the scheduled tasks in a separate thread. It uses thestop_event
to stop the scheduler thread when needed. - The
scrobble_new_track
function is defined to check the Spinitron page for the currently playing track. It fetches the HTML content of the Spinitron page, extracts the track information (artist, song, and release), and compares it to the last scrobbled track. If the current track is different, it scrobbles the track to Last.fm using thenetwork.scrobble
method. - The
index
route renders the HTML page with a form for users to input the Spinitron URL. - The
submit
route is triggered when the user submits the form. It extracts the Spinitron URL from the form data, performs an initial scrobble, and returns a message indicating the result. - The
latest_scrobble
route returns the most recently scrobbled track in JSON format. - The
scrobble_new_track
function is scheduled to run every minute using theschedule
library. - The scheduler thread is started, and the Flask web application is launched.
- If the Flask application is terminated (e.g., by pressing Ctrl+C), the scheduler thread is signaled to stop, and the script gracefully shuts down.
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.