Music Cards: RFID cards + Spotify + Raspberry Pi

I first saw the Spotify Box project a couple of years a go, even before the Raspberry Pi was released to the market. Since then, I have been trying to replicate this idea of using physical objects to select the music that you want to listen.

After a couple of attempts, by the end of 2014, I was able to have a working version and it turned out to be very simple. Just a few lines of python code and usb connected hardware (not even soldering!). The idea is to use RFID cards that are associated to a Spotify URI to start playing a song, album, playlist, etc… in a Raspberry Pi.

So, here’s what you will need if you want to create your own version:

Hardware (~80 USD)

  • Raspberry Pi (any version, as long as you are able to connect it to the internet). Don’t forget the power supply!
  • An 125 kHz RFID card reader. This one is incredibly cheap and it works perfectly.
  • 125 kHz RFID cards. This is the best deal I have found.
  • (Optional) A sound card. The Raspberry Pi has audio output, but the quality is not very good. For less than 10 USD you can get a decent result, like this one. There are better options as well, like the hifiberry.
  • A speaker, receiver, headphones or whatever you want to use to listen to the music.

The connections are pretty obvious. Just connect the RFID reader to the USB port and the sound card too.

Software

To handle the connection to Spotify, I use the image from Pi Musicbox. You can follow the instructions in their website to install the image to the Raspberry Pi. Remember to enable the SSH connection in the settings. Now, if you want to use another board (Beagle Board Black, for example), you can just install Mopidy, which is the base of Pi Musicbox. It creates a music player daemon (MPD) and a web server, so it also provides a web interface to control your music.

To read the cards and control the MPD, I wrote a script that can be found here. The dependencies are listed there. First run ‘python config.py’ to configure the card reader. Then run the script called add_cards.py, where you can assign an Spotify URI to a card number using the reader. You can get the Spotify URI in the Spotify desktop app by right-clicking any song, album, playlist or radio station that you want. After adding some cards and playlists, run ‘python box.py’ and you are all set. All the code is open source and you are more than welcome to contribute!

Last thing is that you may want to include the script box.py to the startup. You can do so by following this tutorial for example.

If you have any questions, comments or improvements I am more than happy to hear them!

140 thoughts on “Music Cards: RFID cards + Spotify + Raspberry Pi

  1. Hi Francisco, is there a simple documentation about your scripts? I have problems to connect the RFID cards with Spotify URLs. Thx for your help

    1. Hi Steph,

      I don’t have a documentation yet. But if you have any questions, I am happy to help. Also, a good source of documentation is the python-mpd2 library (http://pythonhosted.org/python-mpd2/index.html).

      You said you were having trouble with the Spotify URLs. The system works with URI (i.e. spotify:track:7iN1s7xHE4ifF5povM6A48) that are different from the URLs. Are you sure that is not the problem?

      Francisco

      1. Hi Francisco,
        thx for your fast reply. My problem is to add the URI with your script. After I put the card to the reader the raspi shows me the ID of the card but then nothing happens. If I try to enter the URI afterwards it is not possible (I start to enter the first letter than the letter appears several time). What is the next step after putting the card to the reader? I’m really sorry to ask you that trivial stuff but I’m not a raspi or LINUX specialist.
        Thx again for your help.
        Steph

      2. Hi Steph,

        That is probably because your card has less than 10 characters per ID. You can count the number of character of the ID and then change line 14 of readtest.py accordingly.

        Hopes this helps. If it doesn’t let me know!

        Francisco

  2. Hi Fransisco, thanks a whole lot for sharing!

    I’m currently working on a music player for a person with autism and poor motoric skills, and this is exactly what I have been looking for. This will make it possible to enjoy music without getting frustrated over scratched CDs, flimsy player lids, tiny buttons etc. Hopefully I’ll be able to implement physical buttons for next/prev/play/stop as well.

    Regards
    Thomas

    1. Hi Thomas,

      That is a very cool application! Let me know how it goes. You can also assign different cards for next/play/pause instead of buttons. In the code the play/pause is already implemented and you can add the others very easily.

      Francisco

    2. Hi fsahli – amazing work!!! Wooooow. My Daughter gets a oldschool radio were she can listen to her audiobooks via spotify. All with no tablet/phone (she is three).
      Thomas and Fsahli, did you get any further with Pause Play Volume up and down rfid cards? I tried with no success .
      Greetings and thanks

      1. Hi Julian,

        Thanks! And is great to hear that you can use it for such a cool project!

        The pause card is already built in the code. Just add a new card, and instead writing a new spotify playlist, type “pause”. The volume up or down shouldn’t be hard to include. You would need to edit the box.py code around line 46. Check the python-mpd2 package documentation for the exact command.

        Best,

        Francisco

      2. Hi Julian, did you manage to get the volume change to work?

        I just found:

        MPDClient.setvol(vol)
        Sets volume to VOL, the range of volume is 0-100.

        I don’t want to set the volume to a specific target but de- and increase the volume in steps of 10 or 5…

        Best regards,
        goeste

      3. Hi goeste,
        until now i couldn´t manage the volume. My doughter don´t need/ask for it (until now ;)).
        I wanted to create a silent, middle, loud card. That would be enough. When somebody has a solution, i would be soooo happy.
        I also tried via GPIO and other tools… but was not practicable because it was not stable….
        So far from Nuremberg
        Saludos
        Julian

      4. Hi Julian,

        I got it working!!!

        use the following code where you can ad other commands and name the cards volup/voldown, for example:

        elif plist==’voldown’:
        client.status()[‘volume’]
        client.status()[‘state’]
        level = int(client.status()[‘volume’]) – 10 #change to desired decrease amount
        level = max(min(level, 100), 0)
        client.setvol(level)
        client.status()[‘volume’]
        elif plist==’volup’:
        client.status()[‘volume’]
        client.status()[‘state’]
        level = int(client.status()[‘volume’]) + 10 #change to desired increase amount
        level = max(min(level, 100), 0)
        client.setvol(level)
        client.status()[‘volume’]

        Best regards from Frankfurt!
        Felix

      5. Greeeaaaatttttttttttttt!!
        I will try it as soon as possible!
        Grüße aus Nürnberg

  3. I’ve run into the same problem as Steph, and have edited readtest.py using nano on the RPi. It now says “Put the card in the reader” and reads the card but then does nothing. If I press enter, it outputs X or blank. When trying to enter the Spotify URI it looks like this:
    s
    spp
    oo
    ttt
    ii
    ff
    yz

    If I keep pressing enter, eventually it outputs “Specify Spotify UIPut the card in the reader”

    1. Hi Thomas, I still have the same problem you describe above and I couldn’t fix it yet. I also tried to change line 14 of readtest.py because Francisco mentioned that the length of the RFID ID’s could be the problem. But it doesn’t fix the problem. If you find a solution and you fixed the problem please give me note. Thx.

      1. Hi Thomas and Steph,

        I am sorry to hear that is not working. Can you give more details? A screenshot of program running and a picture of card code would be great.
        Also, are you using an external keyboard connected to the Raspberry Pi? Because it sounds like the python is script is capturing both the card reader and the keyboard as the same. I use ssh to connect to the Raspberry and that might be the cause.

        Francisco

    1. Got SSH to work, RFID reader connected direcly to Pi but when running add_card or readtest I now get
      OSError: [Errno 2] No such file or directory: ‘/dev/input/event1’

      1. That should be easy to solve. Probably the reader is in ‘/dev/input/event0’. If event0, doesn’t work try another number. You can see all the options typing ‘ls /dev/input/event*’ in the terminal.

        Hope this helps!

  4. I had the same problem like Thomas. After I changed ‘/dev/input/event1’ to ‘/dev/input/event0’ it worked. Now the script reads the card ID and displays the ID (and the request) like this:

    0
    0
    0
    0
    5
    5
    1
    3
    6
    7
    2
    Specify Spotify URI

    If I copy the Spotify URI the ID and the URI is written correctly to the CSV-file. What are the next steps afterwards? What do I need to do if I want to start the Spotify URI’s with the cards?

    Thx so much, Steph

    1. Great!

      I am assuming that you’re logged in as root, if not add sudo before every command. Now you can start a screen (just type ‘screen’ in the terminal, if it’s not installed, type ‘apt-get install screen’) and then type ‘python box.py’. The screen keeps running even if you close your ssh session. It should work now.

      Also, Musicbox comes with a web interface. You might want to make sure that you can play music from there before you try running box.py. You can access the web interface by typing the IP address of the Pi in a web browser.

      Finally, you may want to add the command ‘python box.py’ to the startup, so you don’t have to log in an start it again every time you reboot. There is a link to a tutorial to do this in the blog post.

      Let me know if it works!

      1. Hi Francisco, thx again for your fast reply. Screen was installed and I can start the python script box.py. If I type the command ‘sudo python box.py’ the cursor jumps into the next line and nothing happens. Than I put the card to the reader and the card ID is displayed as one number per line. But the linked Spotify playlist doesn’t start. The ID and the spotify link is written correctly in the cardlist.csv and I can start the playlist with the web interface. But the card doesn’t start the playlist. Do you have any idea what the problem could be? Cheers, Steph

    1. Same problem here (I’ve installed csvtool to check card id and spotify URI, but have not been able to find the correct file path to check the contents of cardlist.csv.) After typing ‘python box.py’ (included below) and swiping the card I get this:

      root@MusicBox:~/music-cards# python box.py
      0
      0
      0
      6
      8
      1
      3
      4
      3
      7
      X

      ..then nothing. Web interface works as it should. Very grateful for all your help so far! it has been essential as I could hardly spell Linux before deciding to try this.

      Thomas

      1. Hi Thomas and Steph,

        Thanks for all your input. After all these problems that you have mentioned, I decided to improve the code. I uploaded a new version to the GitHub repository. It should be much more robust. Now it should work for all card code lengths.

        Try updating the code and let me know how it goes. You need to first run ‘python config.py’ to select where is the reader. Then you can run ‘python box.py’ and hopefully this time will work!

        Best,

        Francisco

        PS: To see a .csv file, just type ‘more cardList.csv’

  5. Thanks again Francisco, great job! It now worked beautifully on the first try 😀 I’ll update when all the components have been mounted in the enclosure.

    Thomas

  6. Hi Francisco,
    sorry but I still have a little problem with your script box.py (listed in the rc.local file). After I start the Raspi the script starts automatically and works fine with a network cable. If I use a wireless USB adapter (EDIMAX EW-7811UN Wireless USB Adapter) the script works one time after I started the Raspi. Afterwards the reader reacts to a new RFID card (sound is audible) but nothing happens. If I start the script manually again it works perfectly. Do you have any idea what the problem could be?
    Furthermore I would like to use your awesome scripts to play local music files saved on the SD card. Is that possible? Or do you have any idea how it could work?
    Thank you so much again.
    Cheers, Steph

    1. Hi Steph,

      I haven’t tried the script with a wi-fi adapter, so I can’t help you that much. Did you the boot log for any errors? Maybe you can try placing your script in init.d instead of rc.local?

      I know it is possible to also include local files, because they also have an URI, but I don’t know what it is. For a single file I am pretty sure it is the path to the file, but for a playlist I don’t know. Once you have the URI, you can use the same script add_card.py to associate cards with playlists.

      1. Hi, if I restart / start the Raspi your script is running but I figured out that if I put a RFID card on the reader the internet connection gets lost. The connection comes back after 3-5 seconds but than the script doesn’t work any longer. I assume that the mpd client reference gets lost with the internet interruption and never comes back. If I start your script manually afterwards everything works perfectly from this point on. Is there any possibility to reconnect to the mpd client reference after loosing the internet connection for a while? Cheers

      2. Hi Steph,

        It sounds like you may have a power problem. Are you using a 2A power supply? Wi-fi adapters use a lot of power. The script connects to the MPD server every time an instruction is sent, so I don’t think is the script. Check if mopidy crashes, which is the MPD server. You can check if it is running by tipping ‘ps aux | grep mopidy’.

        Francisco

  7. Hello together,
    i have a Problem with me RFID Reader. He works on Event0. I changed the Setting in the readtest.py File to /dev/input/event0 but it did not work. Please help me, I want to build a Player for my childrens.
    thanks
    yves

    1. Hi Yves,

      I think you are using an old version of the code. The file readtest.py is not longer used. When did you download the files? Did you run python config.py first?

      1. Hi,
        i download yesterday.. also i think its the new version… i start with config.py and the add_card.py!?
        greets

      2. no, there is no error. it still waiting for the card..at maçbook the reader is okay.

  8. i installed new.. now he write this
    oot@MusicBox:~/music-cards# python add_card.py
    Traceback (most recent call last):
    File “add_card.py”, line 1, in
    from readtest import *
    File “/root/music-cards/readtest.py”, line 8, in
    dev = InputDevice(‘/dev/input/event1’)
    File “/usr/lib/python2.7/dist-packages/evdev/device.py”, line 93, in __init__
    self.fd = os.open(dev, os.O_RDWR | os.O_NONBLOCK)
    OSError: [Errno 2] No such file or directory: ‘/dev/input/event1’

    my reader is in event 0 and i do the config before

  9. root@MusicBox:~/music-cards# python config.py
    Choose the reader from list
    0 Barcode Reader
    Device Number: 0
    root@MusicBox:~/music-cards# python add_card.py
    Traceback (most recent call last):
    File “add_card.py”, line 1, in
    from readtest import *
    File “/root/music-cards/readtest.py”, line 8, in
    dev = InputDevice(‘/dev/input/event1’)
    File “/usr/lib/python2.7/dist-packages/evdev/device.py”, line 93, in __init__
    self.fd = os.open(dev, os.O_RDWR | os.O_NONBLOCK)
    OSError: [Errno 2] No such file or directory: ‘/dev/input/event1’
    root@MusicBox:~/music-cards# python CardList.py
    root@MusicBox:~/music-cards# python box.py
    Traceback (most recent call last):
    File “box.py”, line 3, in
    from readtest import *
    File “/root/music-cards/readtest.py”, line 8, in
    dev = InputDevice(‘/dev/input/event1’)
    File “/usr/lib/python2.7/dist-packages/evdev/device.py”, line 93, in __init__
    self.fd = os.open(dev, os.O_RDWR | os.O_NONBLOCK)
    OSError: [Errno 2] No such file or directory: ‘/dev/input/event1’

  10. thank you for the new files. I dont have any errors now. But my Reader gives no reaction?? Today I order a new one, may be is this better.
    Or you have any Idea?

    Greets yves

  11. okay.. now it works. i used the wrong dc adapter for my raspberry. I used a handy charger, the Reader hasn´t enough power. Now it workes perfect. Thank you for this perfect tool

  12. Hi Fransicso,
    I love this project (looks like the Jooki Product on Kickstarter does something similar right now).
    I have no experience with Raspberry so far, but I think about getting one for this project.
    My question: To add a new Playlist, do I need to attach a keyboard and screen to the Raspberry? Or is there some kind of web server running on the Pi that I can log in to and add playlists remotely?

    Also, it is possible to output music to a different device via Spotify Connect, like a Chromecast?

  13. I want to use this to play a few local audio files. However, how can I get their URI’s? Or is it not going to work for anything other than spotify?

  14. Hola Francisco.

    Gracias por el tutorial, pero no consigo que me funcione, yo tengo un modulo que no va por USB (NFC RC522) y al lanzar el config.py no me reconoce el dispositivo.

    Muchas gracias
    Luis

  15. Hello Francisco! I’m using the newest version of volumio and a raspberry pi 3. I have had pimusicbox on my pi before, but it runs really bad, and volumio works better than a dream atm.

    Here is the first error I get when I run add_cards.py

    Traceback (most recent call last):
    root@volumio:~/rwid2# sudo python add_card.py
    Traceback (most recent call last):
    File “add_card.py”, line 5, in
    cardList = CardList()
    File “/root/rwid2/CardList.py”, line 8, in __init__
    self.cardList = self.readList()
    File “/root/rwid2/CardList.py”, line 11, in readList
    with open(self.path + ‘/cardList.csv’, mode=’r’) as infile:
    IOError: [Errno 2] No such file or directory: ‘/root/rwid2/cardList.csv’

    1. hello Alexander,
      Did you manage to get the scripts working with volumio? I had the same problem with the CardList.csv error, but I just created the file in the dir with the python scripts and it was ok after that.

  16. I changed the name of CardList.pyc to cardList.csv to get past the nameerror, and now I’m getting:

    root@volumio:~/rwid2# sudo python add_card.py
    Traceback (most recent call last):
    File “add_card.py”, line 5, in
    cardList = CardList()
    File “/root/rwid2/CardList.py”, line 8, in __init__
    self.cardList = self.readList()
    File “/root/rwid2/CardList.py”, line 11, in readList
    with open(self.path + ‘/cardList.csv’, mode=’r’) as infile:
    IOError: [Errno 2] No such file or directory: ‘/root/rwid2/cardList.csv’
    root@volumio:~/rwid2# sudo python add_card.py
    Traceback (most recent call last):
    File “add_card.py”, line 5, in
    cardList = CardList()
    File “/root/rwid2/CardList.py”, line 8, in __init__
    self.cardList = self.readList()
    File “/root/rwid2/CardList.py”, line 13, in readList
    cardList = {rows[0]:rows[1] for rows in reader}
    File “/root/rwid2/CardList.py”, line 13, in
    cardList = {rows[0]:rows[1] for rows in reader}
    IndexError: list index out of range

  17. Hi Alexander,

    There is a bug in the code that is causing your problem. I never noticed it because I had my cardList.csv for a long while. I will fix the code soon, but I think you can get around it by running “touch cardList.csv”. This command will create an empty to store the playlists and the code should run fine.

    Let me know how it goes.

    Francisco

    1. Hello 🙂 The touch command works great, but now I get “Could not play playlist spotify:user:taylorsawyerr:playlist:5P2CFLqEk9CMelH6vICd” on all the playlists I add.

      Also it says “type q to quit” but whenever you try to exit the python thingie it just starts going on new lines forever, not responding.

      Thanks for looking into the project! 🙂

  18. Hello,
    thank you for that great project.

    I am building my own Musicbox. I just want to start local mp3-playlists for files stored on the sd card. So far everything is working. I can start playlists and songs via website.
    When I start box.py, it says, that “Could not play playlist”. I am assuming, that I have to enter the playlist in the file cardlist.csv a specisal way (not just “playlist_name.m3u”).. But I don’t know how. Has anybody an idea, how I can fix that problem?

    Greetings from Marburg, Germany
    Micha

  19. I think I maybe found why the problem is occuring, but I havnt found out how to fix it yet. When scanning the car it connects fine, but i think it is happening when using mpdclient.play() or mpdclient.add(). Here is the error in the volumio.log:

    2016-12-30T23:34:12.902Z – info: [1483140852901] Received update from a service different from the one supposed to be playing music. Skipping notification.Current spop Received mpd
    Here is the whole log:

    2016-12-30T23:34:12.884Z – info: [1483140852884] —————————— 57ms
    2016-12-30T23:34:12.885Z – info: [1483140852885] parsing response…
    2016-12-30T23:34:12.887Z – info: [1483140852886] ControllerMpd::parseState
    2016-12-30T23:34:12.897Z – info: [1483140852887] ControllerMpd::pushState
    2016-12-30T23:34:12.898Z – info: CoreCommandRouter::servicePushState
    2016-12-30T23:34:12.899Z – info: [1483140852898] CoreStateMachine::syncState
    2016-12-30T23:34:12.900Z – info: [1483140852900] CorePlayQueue::getTrack 0
    2016-12-30T23:34:12.902Z – info: [1483140852901] Received update from a service different from the one supposed to be playing music. Skipping notification.Current spop Received mpd

      1. Hello Francesco, thanks for your reply 🙂
        I tried and I can play with an mp3, i changing cardlist.csv with “0008875262000,file:/music/MusicBox/born.mp3”
        I can not play the playlist, instead of “file:” what command should I use for the playlist?

      2. Hi Maox, Francisco,

        Have you got the local playlists to work by using the full path of the playlist? I have not…

        But I got it to work when I do the following
        1. Modify box.py line 26, “client.add(plist)” instead of “client.add(plist)”
        2. When assigning cards (with add_card.py), I use the playlist name as I see it in the MusicBox GUI (i.e. no path / .m3u extension)

        I guess this breaks the support of Spotify playlists though, but it does the job for me.

        Thanks a lot for this great script Francisco.

        Cheers,
        Jon

      3. Hi Maox, Francisco,

        Have you got the local playlists to work by using the full path of the playlist? I have not…

        But I got it to work when I do the following
        1. Modify box.py line 26, “client.load(plist)” instead of “client.add(plist)”
        2. When assigning cards (with add_card.py), I use the playlist name as I see it in the MusicBox GUI (i.e. no path / .m3u extension)

        I guess this breaks the support of Spotify playlists though, but it does the job for me.

        Thanks a lot for this great script Francisco.

        Cheers,
        Jon

      4. Hi, I could solve the issue of local playlists the same way Jon described:

        1. Modify box.py line 26, “client.load(plist)” instead of “client.add(plist)”
        2. When assigning cards (with add_card.py), I use the playlist name as I see it in the MusicBox GUI (i.e. no path / .m3u extension)

        Now I’ve got following problem:
        I can see in the cardList.csv that all cards (currently 2) are read correctly and a corresponding m3u file is mapped.
        Anyhow as soon as I have more than 1 card in the csv it will not work with the 2nd or 3rd etc. card…
        it just says:

        Ready: place a card on top of the reader
        Read card 0002562119
        Playlist versuch
        Connecting…
        Connected!
        Could not play playlist versuch

        Does anybody have an idea?

      5. Hi Cyrus,

        I have no experience with local playlists, but you could try to debug the code in a python shell doing the following:

        from box import *

        client = connectMPD()
        client.stop()
        client.clear()
        client.load(‘versuch’)
        client.play()

        That should give you more information about the error.

        I have to mention that you need to be in the same folder as the file box.py and you can start a python shell just by typing python in the command line.

        Let me know how it goes.

        Francisco

      6. Hi Francisco,

        I don’t know why and what has changed, but this little debugging helped…
        the code is now running, without any change (?)

        Thanks anyway…

        Next step: GPIO Button support

      7. ok, now I was able to reproduce the behaviour.
        After adding a new card an m3u playlist a reboot is needed.
        No reboot: not playing the latest playlist…

      8. hi Cyrus,

        when i use the RFID card i get:
        Ready: place a card on top of the reader
        Read card 0002912654
        Playlist /music/playlists/KdL
        Connecting…
        Connected!
        Could not play playlist /music/playlists/KdL

        any idea what happens? i tried to debug, but got no errors. in box.py i already use the client.load() command instead of client.add()

        in webfrontend i see the Playlist (after reboot) and it works.

        do your GPIO working?

  20. hi,

    looking at following your code, i am following the config.py part. i initially got an error as i had no module name evdev so i downloaded it now i am getting a NameError: name ‘raw_input’ is not defined was wondering if you could help many thanks!

    1. managed to change raw_input to input and it seems to work however the only device showing up in my usb is values 0U, 1U and 2 SIGMACHIP USB Mouse. When removing the keyboard just the mouse shows is there something that can be done to pick up the rfid as a device? sorry for all the questions

      1. still no rfid recognition- i am using a id20la and a sparkfun rfid usb if that makes a difference?

  21. Can I just say !!! amazing work !!!

    If you dont mind giving me some help ? i’m having no problem getting one song to play “spotify:track:2jTidefcsTu6VQhpIImJrt” but no joy with a full playlist ? and i can find no other links, is there some syntax i’m missing ?

      1. thanks so much, i was using the web player, just installed the app and found the share button.

        sorry for wasting your time

  22. Hello Francisco,
    thank you very much for sharing this project. I set it up and it’s working wunderful. My son will be very happy with his Musicbox..
    I had the most problems with the autostart of the box.py. I put it in the cron-List using this tutorial: https://www.raspberrypi-spy.co.uk/2013/07/running-a-python-script-at-boot-using-cron/

    Again, thank you very much, without you’re code I wouldnt be able to get this nice thing done.

    Greeting from Dortmund in Germany, Sebastian

    1. Hi Sebastian,

      I was able to make it auto start with by adding editing rc.local (root@MusicBox:/etc# nano rc.local). My file looks like this (what is inside sharp brackets):

      [#!/bin/bash
      #
      # rc.local
      #
      # This script is executed at the end of each multiuser runlevel.
      # Make sure that the script will “exit 0” on success or any other
      # value on error.
      #
      # In order to enable or disable this script just change the execution
      # bits.
      #

      /opt/musicbox/startup.sh 2>&1 | tee /var/log/musicbox_startup.log
      python /root/music-cards/box.py &
      exit 0]

      I hope this helps.

      Regards,
      Stig

    2. Hi Sebastian,
      how long do you have to wait until the player starts to play? The Musicbox for my doughter takes 60 Seconds +/- maybe its because of my autostart…. is yours faster?

  23. What a brilliant setup. I’ll be gifting this to my dad who does not want to use smart devices to control his music. With this setup I can make playlists for him that are just as easy to play as a cd:-)

    Now, I’m not sure if running “updatepip.py” is wrong, but it definitely renders the installation useless and leaves me with “could not connect to MPD server”. After the update MusicBox is version 0.7.0RC5

    Any thoughts? I can just reinstall everything and not run the update – but shouldn’t I be able to update the whole system?

    Thanks again for you efforts – and help:-)
    Regards,
    Stig

    1. Yes, in line 47 of box.py add:

      elif plist==’next’:
      client.next()

      Then, add a card and instead of playlist URI, type “next”.

      PS: I haven’t tried this code, but I don’t see why it wouldn’t work.

  24. Hello Francisco,

    Thank you very much for sharing this awesome project.
    I have an issue with config.py which doesn’t recognize my HID Omnikey 5021 CL reader, although I can see it typing “lsusb”. Any suggestions?

    Thank you for your help 🙂

    1. Hi Victor,

      I am not sure about the specifics of that reader, but the one I used acts like a keyboard. I am pretty sure that, because of the library evdev, only this kind of readers will work with the code. Did you install the driver?

      Best,

      Francisco

      1. Hello Francisco,

        Yes I installed the drivers for this RFID reader. But it’s beyond my abilities to hack your code into making it work, so I’ll just get another reader.

        Thank you for your help!

  25. Hi,

    first off: I am blasted away… exactly I wanted for my twins 🙂

    just a quick question, when a card is set to a playlist containing an audiobook, will this be shuffled or not, because I read that playlists are shuffled in a post at the beginning. If an audiobook is shuffled, is there a way to not shuffle audiobooks?

    Best regards,
    Felix

    1. Hi Felix,

      You can comment lines 27 and 28 in box.py to avoid shuffling. This will turn it off for everything. I don’t know if there is an specific marker in the URI that you can use to differentiate between playlists and audiobooks.

      Francisco

      1. Alright, than i just create a ‚shuffle‘ card top turn on and of shuffle 😉 thank you Francisco!

        Saludos, Felix

    2. Any chance you could share your complete box.py that has volup, voldown and shuffle cards working? I got the pause card working but am having trouble with the others. 🙂

  26. I’m successfully installing the dependencies after enabling SSH, but running ‘python config.py’ immediately after gives me an error. No such file or directory.

    1. It seems as though its not creating /music-cards directory. It says successfully installed mpd2, but I cannot get to /music-cards. No such file or directory. Forgive my ignorance. I am quite new.

  27. hi guys. do you have the same problem: uris with user playlists don t work anymore….? normal tracks and album no problem….

      1. Thanks Miguel for your feedback.
        I am not sure to try the fix, because i have for my doughter the raspberry and it is already booting veryyyyy long…. (for a 3 year old girl sometimes tooo long:) )

        i will check from time to time… i sorted out all Playlists….

        Have a nice sunday
        Julian

    1. The playlists issue is something related with changes in spotify api. The fix as i know seems to use the web api.
      For this project i have a pi b+ and the music starts in about 1 second if the processor is only waiting for mopidy.

  28. Hi Francisco,
    I’ve set everything up. If I manually enter the playlist, after the comma of the card number in the csv file, it scans and begins playing the spotify album no problem. But when running add_card, i run into this:

    Place the card in the reader
    0006322291Specify Spotify URI, q to quit
    Place the card in the reader

    If i then try to type anything at all and press enter, it goes to the next line in the console. More typing and then enter goes again to a new line. q doesn’t quit. q + enter doesn’t quit either. ctrl c is the only way to get out. Then I can at least go and edit the csv file manually. In that csv file, I then see

    0006322291,0006322291

    Just wondering if you’ve seen this issue before. I have a 2amp psu, no wireless keyboards, just a corded mouse. box.py works once I manually edit the csv file.
    Thanks for your time
    Luke

    1. Hi Luke,

      I am not exactly sure what is happening, but it looks like your RFID reader is acting as a keyboard. Are you doing this over ssh?

      Francisco

      1. I think it is acting as a keyboard. It seems to be adding the enter key after the 10 digits. Is this not the intended way? How should it normally act? I can SSH from my pc. Do you mean I should attach the rfid reader to the pc to add cards ?

        Thanks for your patience.

  29. Hello,

    İt works perfect with spotify tracks and albums but unfortunately playlist doesnt work.
    when you assign spotify playlist URI to cards it says “Could not play playlist”
    we are hoping to see someone fix it soon

  30. Hi,
    I’m not sure if I’m doing Right. I connect with my Windows PC via putty to the Raspberry. Thats okay and it works. I’ve installed the python-evdev_0.4.1-1_armhf.deb and then the pip install python-mpd2. Thats okay. But when I enter /music-cards# python config.py I get the message: No such file or Directory. But if I look with WinSCP, there is a Folder with the Name Music-Cards in root, an in this Folder there is the file config.py. What is my mistake?

    1. Are you sure you are in the right folder? you can check the contents of a folder typing ‘ls’. And you can check in which directory you are working typing ‘pwd’ (print working directory).

      1. Thanks I was in the wrong Folder. Now the config is done, but when I try my RFID Card, I get the error message: Could not play playlist spotify:user:XXXX:playlist:5pagngRBU3lw6ojGeYisYb

        I have a Spotify premium account and I’ve shared my Playlist. When I try to play some Spotify tracks in the MusicBox Webclient it works.

    1. Yes with a track or album it works.
      I’ve another question, is there a way, that when I connect the RFID Card the Music will play, but when I remove the card from the RFID Reader, the Music will stop?

  31. Hi,

    first, let me thank you for your script and the how-to, it worked perfectly on the first try!
    I was wondering, if it’s possible to add a second command into the cardList.csv file, so that you can add the shuffle option to one specific album.

    like this: 0001234321,spotify:album:XXX123456789XXX,”shuffle”

    (i already added the lines for next,shuffle,volup … in box.py like goeste did in his pastebin link (April 13,2018))

    If this would be possible it would be great, I would love to add a shutdown command after a specified time so that my pi shuts down after I add a card and a song is played to its end…

    Thanks in advance,
    Joachim

  32. Hi Joachim,

    Thanks! It is definitively possible, but I don’t have the time to do it now. It is not difficult, but you would need to modify CardList.py and box.py as well.

    Francisco

  33. hello,

    Is there anyway to use mpc commands for my RFID cards. i couldnt make it work.
    for example when i add

    0002876469,mpc toggle

    to my cardList.csv it didnt control my mopidy.

  34. Hi! When I run the config.py script I get this error:
    Traceback (most recent call last):
    File “config.py”, line 2, in module
    import InputDevice, list_devices
    ImportError: No module named InputDevice

  35. Hi fsahli, I started over from the beginning. reinstalled the musicbox_v0.7.0RC7 image, changed directory to MusicBox, then installed wget http://dl.piwall.co.uk/python-evdev_0.4.1-1_armhf.deb. Then installed pip install python-mpd2 in same directory. I get the same error message:

    root@MusicBox:~# cd /music/MusicBox
    root@MusicBox:/music/MusicBox# python config.py
    Traceback (most recent call last):
    File “config.py”, line 2, in
    from evdev import InputDevice, list_devices
    ImportError: No module named evdev

  36. I figured it out. it all works! Thanks for your help. Your project was the best I have seen on this topic. At some point I will write up all the errors I ran into and how they were solved for complete documentation for someone who is not a programmer.

  37. Hi guys,
    did anybody managed to get “spotify connect” working again?

    Has somebody a hint for resizing the microsd card partition to put the mp3 files on it?

    thanks at all…. best raspi project ever!!
    ju

  38. Which OS is used for this? I am currently using raspbian with a mopidy app installed. Currently running into issues with storing the add card in the pyc from the read-card.py. Also not sure if raspbian/mopidy will work, open to what other OS I can use. I tried musicbox but could not figure out how to install the python script and run the script with music box since it appeared to me that it was its own OS that ran as a music server. All help is greatly appreciated (:

    1. Hi Andrew,

      As long as you can install mopidy, I think it should work. Read the comments above, because there are many people with an issue when adding the first card.

      Best,

      Francisco

  39. Wow ! Thanks Francisco, your scripts work really well. Also thanks to the many comments here, I also had a probmlem playing local files. Someone suggested changing the “client.add” method to “client.load” in box.py, This worked for me, I could then play local mp3’s from a playlist, but internet radio streams stopped working, I presume they need the client.add method. I modified box.py with a few lines that look for “http:” in plist and to use the add method if its found, and the load method if is isnt.

    Its probably not the best way, Im not very good with python, also It wouldnt play until i removed the section of code that looks for a pause card. I hope this helps anyone with similar issues

    Regards
    Lee

    #!/usr/bin/env python
    from mpd import MPDClient
    #from readtest import *
    import re
    from CardList import CardList
    from Reader import Reader
    import sys

    def connectMPD():
    try:
    client = MPDClient() # create client object
    client.timeout = 200 # network timeout in seconds (floats allowed), default: None
    client.idletimeout = None
    print “Connecting…”
    client.connect(“localhost”, 6600)
    print “Connected!”
    return client
    except:
    print ‘Could not connect to MPD server’

    def play(client, plist):
    try:
    client.stop()
    client.clear()

    #NEW SECTION TO PLAY HTTP STREAMS AND LOCAL MP3s
    if re.match(‘http:’, plist, flags = 0):
    client.add(plist) # only works for internet streams
    client.play()
    else:
    client.load(plist) # only works for local files
    client.play()
    fi

    if re.search(‘playlist’,plist):
    client.shuffle()
    client.play()
    except:
    print ‘Could not play playlist %s’ % plist

    reader = Reader()
    cardList = CardList()

    print ‘Ready: place a card on top of the reader’

    while True:
    try:
    card = reader.readCard()
    print ‘Read card’, card
    plist = cardList.getPlaylist(card)
    print ‘Playlist’, plist
    if plist != ”:
    client = connectMPD()
    if plist==’pause’:
    client.pause()
    else:
    play(client, plist)
    client.close()
    except KeyboardInterrupt:
    sys.exit(0)
    except:
    pass

    1. Hi, thanks for your script mod. I would like to add a local playlist too… buy no matter what I do with cardList.csv, the .m3u doesn’t work. Could you give me an example of your cardLlist.csv and where to place the .m3u? Thanks.

      1. Hi, i was able to play local mp3 and m3u files. For the m3u files you need the client.add(plist) function. I changed the code in box to:

        if re.match(‘file:’, plist, flags = 0):
        client.add(plist)
        else:
        client.load(plist)

        FYI i only use this script to play mp3 files from an usb medium. So it checks if its a file or a playlist an either adds the track or loads the playlist.

        The entry in the cardList.csv is:
        0123456, nameOfThePlaylist

        I created first my own m3u file and loaded it with the GUI. It started playing, but i couldn’t get it to work with the RFID reader.
        So i create with the GUI a new playlist (add tracks to queue and then save as palylist).
        This playlist is called “nameOfThePlaylist.m3u” and located in /music/playlists/
        Now i added a new RFID card and only used the name of the palylist, without path or .m3u extension.

        I also restarted the pi and after that i can start the playlist with the card.

        Hope it can help you a little bit.

        ——————————-
        I also added buttons and everythink works wonderful, except the internet connection because of that i used local mp3s.

  40. Can anyone leave a updated link for a RFID reader and RFID cards are will work for this project? I wanna make sure I can one that are compatible for this project. Thanks!!

  41. Hello Francisco! i’m having an issue with config.py not seeing my RFID reader. I’m connected via GPIO and have successfully written and read using a different script. I just can’t get your script to see my reader? Any thoughts?

    1. Hi, the original script was developed for a USB reader, which acts as a keyboard, so you will need to rewrite parts of the code to make it work with a GPIO reader.

  42. Hi, Francisco — I’ve been working at this for hours and hours now, but am having a tough time.

    I managed to get the github repository downloaded by doing ‘wget https://github.com/fsahli/music-cards/archive/master.zip‘ (because I couldn’t use ‘git clone’ to download as it doesn’t exist on on Pi MusicBox image).

    I was able to run ‘config.py,’ and select the RFID reader. When I now try to run ‘add_card.py,’ I get the following message:
    —————————————
    Traceback (most recent call last):
    File “music-cards-master/add_card.py”, line 5, in
    cardList = CardList()
    File “/root/music-cards-master/CardList.py”, line 8, in __init__
    self.cardList = self.readList()
    File “/root/music-cards-master/CardList.py”, line 11, in readList
    with open(self.path + ‘/cardList.csv’, mode=’r’) as infile:
    IOError: [Errno 2] No such file or directory: ‘/root/music-cards-master/cardList.csv’
    —————————————

    What can I do to resolve this? Anything you can help with would be greatly, greatly appreciated!!

      1. I did this, and that worked! Thank you.

        I’ve hit another roadblock, and was not able to find a solution in the above comments.

        I am able to run add_card.py, and the script then prompts me to place a card on the reader. Once I do, it says “Specify Spotify URI, q to quit”.

        How do I go about assigning the URI to the card? Should I copy and paste the URI into the same line, hit enter, etc.? Or what instead? And then, run box.py next?

        I am so so close to the end, but not there yet—and I would be extremely grateful for your guidance to get me there.

  43. yes, you need to copy/paste the spotify URI and then hit enter. Once you are done adding cards type q and then enter. Then you run python box.py

  44. Hi fsahli, are you using already this? What is your workaround with the spotify api since May 2022?

    Im waiting for the mopidy-spotify solution but… no luck.

    Thanks so much for your time

Leave a comment