MPDで再生中のアーティストと曲名を表示する


Raspberryを使ってMPD(Music Player Daemon)で再生中のアーティスト名と曲名を表示させたいと思っていました。
このページでLCDのケースを紹介しましたが、そこで使っているソフトを紹介します。
まずはpython3用のmpdライブラリをインストールします。
$ sudo apt-get install python3-mpd

$ dpkg -l python3-mpd
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version      Architecture Description
+++-==============-============-============-====================================
ii  python3-mpd    3.0.3-1      all          Python MPD client library (Python 3)

python mpdライブラリを使ったコードは以下の通りです。
基本的なAPIしか使っていないので、python2 + python2用のmpdライブラリでも動きます。

client.connect()でMPDサーバに接続し、
client.idle()で状態変化を捉えて、
client.status()で演奏中かどうかを判定 し、
client.currentsong()でアーティスト名と曲名を取り出しています。
LCD表示用の外部コマンドとしてこちらで紹介しているLCD制御ソフトを使っていま す。

#!/usr/bin/python
#-*- encoding: utf-8 -*-
import sys
import subprocess
from mpd import MPDClient

if __name__ == '__main__':
    argv = sys.argv  # コマンドライン引数を格納したリストの取得
    argc = len(argv) # 引数の個数
    lcd_command="/home/pi/lcd/lcd"

    client = MPDClient()
    client.timeout = 10
    client.idletimeout = None
    client.connect("192.168.111.40", 6600)  # connect to MPD Server

    while True:
        client.idle()
#        print(client.status()["state"])
        if client.status()["state"] == "play":
#            print(client.currentsong())
            artist="artist" in client.currentsong()
            title="title" in client.currentsong()
            if artist and title:
#               print(client.currentsong()["artist"])
#               print(client.currentsong()["title"])
                string=client.currentsong()["artist"]+"-"+client.currentsong()["title"]
            else:
                string=client.currentsong()["file"]
#            print string
            args=[lcd_command,string]
            subprocess.call(args)
        if client.status()["state"] == "stop":
            args=[lcd_command]
            subprocess.call(args)


    client.close()
    client.disconnect()

表示はこんな感じです。


LCDが日本語表示できないので、残念ながら日本語には対応していません。

続く...