はじめに
寝る前にごろ寝PCにてSpotifyで音楽をかけて寝ています。しかし、朝まで鳴りっぱなしなのが気になり、PCでSpotifyのスリープタイマーがあるか調べてみましたが、iPhoneやAndroidの記事しかなく、PC用を見つけられなかったためSpotify Web APIをPythonで使えるライブラリspotipyを使って作ってみることにしました。
環境
$ sw_vers
ProductName: macOS
ProductVersion: 11.1
BuildVersion: 20C69
- python 3.8.5
- spotipy 2.16.1
クライアント登録
- Spotify for Developerにアクセス
- DASHBOARD
- CREATE AN APP
- クライアント名と説明を記入
以上の手順を踏めばクライアントが作成できます。かんたんですね。
Client IDとClient Secretはあとで使用するのでメモしておきましょう。
ユーザ名取得
- Spotipyにアクセス
- ログインして、プロフィール→アカウント
- アカウント情報→ユーザ名
ユーザ名も後で使用するのでメモしておきましょう。
APIを呼ぶ
ここからPythonでプログラムを書いていきます。
まず、Spotify Web APIをPythonで使用するためもライブラリをインストールします。
$ pip install spotipy
spotipyの公式リファレンスを見ながら書いてみます。
scope
はSpotify Web APIのリファレンスを見て使いそうな機能を選択します。
# -*- coding: utf-8 -*-
import spotipy
from spotipy import Spotify, SpotifyOAuth
# Settings
client_id: str = "Client ID"
client_secret: str = "Client Secret"
username: str = "Username"
scope: str = "user-modify-playback-state user-read-currently-playing"
redirect_uri: str = "http://localhost:8080"
auth_manager: SpotifyOAuth = spotipy.SpotifyOAuth(
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri,
scope=scope,
username=username,
)
spotify: Spotify = spotipy.Spotify(auth_manager=auth_manager)
spotify.pause_playback()
Spotifyで音楽を再生した状態でプログラムを実行すると、音楽の再生が止まったと思います。
タイマー機能
上記のプログラムでは実行してすぐに停止してしまうため、タイマー機能を実装します。また、再生していないときに、pause_playback()
を呼び出すと、エラーが帰ってきてしまうので、一応再生中かcurrently_playing()
を呼んで確認します。
タイマー機能はpythonデフォルトライブラリのdatetime.timedeltaを使えばかんたんですね。ついでにコマンドライン引数から入力を受け取れるようにします。
# -*- coding: utf-8 -*-
import sys
from time import sleep
from datetime import datetime, timedelta
import spotipy
from spotipy import Spotify, SpotifyOAuth
client_id: str = "Client ID"
client_secret: str = "Client Secret"
username: str = "Username"
scope: str = "user-modify-playback-state user-read-currently-playing"
redirect_uri: str = "http://localhost:8080"
auth_manager: SpotifyOAuth = spotipy.SpotifyOAuth(
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri,
scope=scope,
username=username,
)
spotify: Spotify = spotipy.Spotify(auth_manager=auth_manager)
start_time: datetime = datetime.now()
stop_time: timedelta = timedelta(seconds=int(sys.argv[1]))
while True:
elapsed_time: timedelta = datetime.now() - start_time
if elapsed_time > stop_time:
break
sleep(1)
is_playing: bool = response['is_playing'] if (response := spotify.currently_playing()) is not None else False
if is_playing:
spotify.pause_playback()
まとめ
Spotify Web APIを使用して、スリープタイマー機能ができました。
githubに全体のソースコードを載せています。ご参考までに。