Run a script when mpd wants to play a song

Hi,
I have built a power strip I can control through USB. Now I have teach my computer how to turn on or off a plug , I would like that it turns on automatically  my speakers when my computer play a song and turns it off when it stops.
As the music is controlled by mpd, I would like to know if it is possible to add this functionality to mpd? Or do I have to tell Alsa to make this work (how?)? Or do I have to make a daemon which will check whether a song is played or not?
Thanks

You would write a simple mpd client for such a task usually. (not sure if perhaps 'mpc' has this built-in already)
Example C-program using libmpdclient that wakes up once mpd plays a song or stops playing:
* Compile: gcc mpdsonglisten.c -o mpdsonglisten -lmpdclient -std=c99
* Run: ./mpdsonglisten localhost 6600 <on_play_script> <on_stop_script>
* Example: ./mpdsong localhost 6600 'echo plays!' 'echo stopped!'
* It will call on_play_script once mpd starts playing,
* and on_stop_script once it pauses, stops or does something unknown.
* Error handling is done by ignoring none-fatal erros and trying to reconnect if
* fatal errors happen.
#include <mpd/client.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
static volatile bool not_ctrlc_pressed = true;
static bool check_error(struct mpd_connection * client)
if(mpd_connection_get_error(client) != MPD_ERROR_SUCCESS) {
printf("Error: %s (Retry in 1 second...)\n", mpd_connection_get_error_message(client));
if(!mpd_connection_clear_error(client)) {
mpd_connection_free(client);
sleep(1);
return true;
return (client == NULL);
static struct mpd_connection * connect(const char * host, unsigned port)
struct mpd_connection * client = NULL;
for(;;) {
client = mpd_connection_new(host, port, 2000);
if(check_error(client)) {
continue;
break;
return client;
void cancel_signal(int signal)
if(signal == SIGINT) {
not_ctrlc_pressed = false;
int main(int argc, char const *argv[])
if (argc < 3) {
printf("Usage: prog <hostname> <port>");
return EXIT_FAILURE;
int previous_sond_id = -1;
enum mpd_state prev_state = MPD_STATE_UNKNOWN;
struct mpd_connection * client = connect(argv[1], strtol(argv[2], NULL, 10));
signal(SIGINT, cancel_signal);
while(not_ctrlc_pressed) {
enum mpd_idle events = mpd_run_idle (client);
if(check_error(client)) {
client = connect(argv[1], strtol(argv[2], NULL, 10));
continue;
if (events & MPD_IDLE_PLAYER) {
struct mpd_status * status = mpd_run_status(client);
if (status != NULL) {
enum mpd_state play_state = mpd_status_get_state(status);
int current_song_id = mpd_status_get_song_id(status);
switch(play_state) {
case MPD_STATE_PLAY:
if (current_song_id != previous_sond_id && prev_state != play_state) {
previous_sond_id = current_song_id;
if (argc > 3)
system(argv[3]);
break;
case MPD_STATE_UNKNOWN:
case MPD_STATE_PAUSE:
case MPD_STATE_STOP:
previous_sond_id = -1;
if (argc > 4)
system(argv[4]);
break;
prev_state = play_state;
if(client != NULL) {
mpd_connection_free(client);
return EXIT_SUCCESS;
(also as gist here: https://gist.github.com/sahib/6718139)
Edit: Added error handling // do not consume 100% cpu when connection fails.
Last edited by SahibBommelig (2013-09-26 18:07:56)

Similar Messages

  • When you want to play a song but it wont play how do you get it to work?

    Please help with the above question!

    Hi,
    Read these links. Does this help.
    http://support.apple.com/kb/PH12283 and http://support.apple.com/kb/ht2519
    Jim

  • Launchd - can it run a script when users log in OR switch?

    I'm hoping to find someone who knows all the gory details of launchd. Here's the why and what: I'm trying to coerce Aperture into letting two users on the same computer share the same Aperture Library, both able to import photos and see and use what the other has done. Initially it is no problem, change the permissions so everyone has read/write/execute, put the Library in a common area, and point both person's Aperture at it. The problem is that Aperture changes permissions of things inside the Library as you use it, and especially when one person imports, the other person can't see that stuff.
    So I want to run a script whenever someone logs in or becomes the active user by fast user switching; the script will simply change ownership and permissions of the library and everything in it to restore full access.
    After days of research and testing, I made a test launchd plist file (this is the configuration file or agent that launchd looks at and runs your script when criteria are met). It sits in /Library/LaunchAgents/, here it is:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
    <key>Label</key>
    <string>org.jim.test</string>
    <key>LimitLoadToSessionType</key>
    <string>LoginWindow</string>
    <key>ProgramArguments</key>
    <array>
    <string>/Library/Scripts/testscript.sh</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>StandardErrorPath</key>
    <string>/Users/jim/Desktop/test.err</string>
    <key>StandardOutPath</key>
    <string>/Users/jim/Desktop/test.out</string>
    </dict>
    </plist>
    The actual test script is sitting in /Library/Scripts/:
    #!/bin/bash
    echo "org.jim.test.plist was run at `date`"
    So if the plist is loaded and the script run, the date and time are written in the test.out file on my desktop. This thing runs great when a user logs in. The problem is, it doesn't run when users switch by fast user switching. In reading the documentation, it was vague about this, whether that could be done; I thought it could.
    Can anyone help with a way to get the script to run when any user takes control by any means? As an added complication, which I'll worry about later, the script has to run as root because it's the only way to get the ownership and permissions changed.
    Thanks,
    Jim

    BobHarris is the MAN. ACLs seem to have worked. I put the Aperture Library in /Users/Shared/ApertureLibrary, restored the regular permissions as best I could (me as owner, staff as group, 755), pointed each person's Aperture to the library, then proceeded with the ACL magic. First I created a group for my wife and I, called 'aperture', in the Accounts preference pane. That was to simplify the ACLs (one entry instead of 2) and so that other users (son) aren't able to muck it up.
    It took one stinking Terminal command (note that 'aperture' at the beginning of the quote is the group, not the program, folder or library):
    chmod -R +a "aperture allow list,addfile,search,delete,add_subdirectory,delete_child,file_inherit,directoryinherit" ApertureLibrary.aplibrary
    I was unsure whether this list of permissions was necessary or sufficient, but it seems to have worked so far. Both users can access the library. I imported a different picture by each user, and the other user could then see and delete the picture imported by the other. This was not possible before.
    Bob, thanks for the great idea. After a little more testing I'll post a complete how-to in the latest "how do we share Aperture" thread, and give you due credit. The bad news is all the launchd fun is over
    Jim

  • I run JMStudio.java and i want to play a mov file but an error happen

    this time i run JMStudio.java on eclipse and when i want to play a mov file but an error happen:
    # An unexpected error has been detected by Java Runtime Environment:
    # EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x033b2890, pid=2652, tid=3096
    # Java VM: Java HotSpot(TM) Client VM (1.6.0-rc-b104 mixed mode, sharing)
    # Problematic frame:
    # C [jmjpeg.dll+0x12890]
    # An error report file with more information is saved as hs_err_pid2652.log
    # If you would like to submit a bug report, please visit:
    # http://java.sun.com/webapps/bugreport/crash.jsp
    i always obtain the result when i use AVReceive3.java to receive mov files transmitted by RTP,and the mov files converted from a list of JPEG image files (JpegImagesToMovie.java) .
    could anyone please give me a help? many thanks

    Did you export the iMovie project to a movie file i.e. .MOV file?
    You said you burned the project to a DVD.  A PC will not be able to open an iMovie project.

  • I want to play a song I bought but when I press play it says I need to authorize my PC but when I  put in my Apple ID it says its already authorized. What should I do to be able to play the song?

    I want to play a song I bought but when I press play it says I need to authorize my PC but when I  put in my Apple ID it says its already authorized. What should I do to be able to play the song?

    Delete and redownload it if doing so is free in your country.
    (94038)

  • HT1711 I have over 100 songs I bought back before mid-2009 when Apple dropped this DRM thing. If I want to play those songs on Sonos, the ONLY way to do so is pay Apple another $25/year for iTunes Match and re-download them??

    I have a Sonos system in my house and suddenly discovered that many songs I bought off of iTunes years ago are 'grayed out' when I try to play them from my iPhone or do not appear as options at all when I try to play them on Sonos from my overall music library.  It's well over 100 songs I bought back before mid-2009 when Apple dropped this DRM thing. From what I think I am reading, if I want to play those songs on Sonos, the ONLY way to do so is pay Apple another $25/year for iTunes Match (which I don't have any interest in) and then re-download them all in iTunes Plus format??

    Matt, 
    I agree it was not all communicated real well, but in your case it will work out.  You missed the program where you could have upgraded 100 tracks for 30 cents each (=$30) but now you can do it via Match (=$25).  It works pretty simply, per this document:
    Can I upgrade my previously purchased music to iTunes Plus?
    Yes. If you subscribe to iTunes Match, you can download your previously purchased music again in the iTunes Plus format. To do so:
    You need to delete the original DRM song from your library first. Doing this enables you to download the song again in the iTunes Plus format from iTunes in the Cloud.
    Click the Purchased tab in the iTunes Store.
    Click Music.
    Locate the artist of the song you want to upgrade.
    Click the iCloud Download icon next to the song you want to upgrade.
    Just don't forget to put the Plus files on your hard drive -- properly backed up of course -- and to cancel the Match subscription before the second year rolls around!

  • IPod classic displays 'No music' after sync, HDD problem? Geschiedenis • Verwijder  So recently I synced my iPod Classic 160 GB like I did so many times and when I wanted to play some music afterwards it couldn't find any files on the iPod anymore. H

    So recently I synced my iPod Classic 160 GB like I did so many times and when I wanted to play some music afterwards it couldn’t find any files on the iPod anymore. However when you look in the settings it displays that ~roughly 90 GB free space is available. Seen the fact that I had about 60 gigs of music this doesn’t seem like a coincidence and I think my music is still somewhere on the ipod but the HDD isn’t recognizing it anymore.
    I’ve tried resetting it, and resetting it to factory settings, which didn’t work. When connected to a desktop it won’t be recognized by iTunes, it displays an error message that the iPod cannot be read and that I have to reset it to factory settings.
    I’ve spent some time researching this problem yesterday and I ran into a myriad of vaguely similar problems didn’t really offer any help. Currently I’m thinking that formatting the iPod might work, and restoring the software afterwards. However this is a rather bold strategy so I’d like to consult you here first.
    Thanks in advance!

    Hi turingtest2,
    Thank you for the info, with formatting my iPod I managed to connect it to iTunes again.
    However..in the page you linked to there is a section about how transferring large amounts of data can dump your library. That seems to be the problem in this case. It won't even allow me to transfer more than 2 gigabytes of music per sync, if I go higher it will dump everything again. Having over >60 GB of music in my library, this is disastrous to say the least.
    Do you think that there is any other solution besides the method you mentioned involving Smart Playlists?

  • My AppleTV 2 when I want to play media from iTunes 10.5 and my AppleTV also has up to date firmware Keeps dropping my "Home Sharing" connection while all other media sources YouTube,Netflix...etc still work?

    My AppleTV 2 when I want to play media from my WinVistaPC 64bit iTunes 10.5 and my AppleTV also has up to date firmware when trying to play media from the "Computer" tab on the AppleTV my  PC and all of the media be it music ,movies or podcasts it tries to load  the spinning thing on the middle of the screen never loads then my PC disappears from the AppleTV and says "From your computer in iTunes login to Home Sharing with your AppleID " so I do that and IT STARTS WORKING! BUT! then after the media finishes playing it regresses back to the same problem and I have reinstalled iTunes and it doesnt resolve anything it says under the advanced tab of iTunes 10.5 that "Home Sharing is ON!" and I have to click "Turn off Home Sharing" then re enter my password again and restart the entire process only to have it let me play 1 media file of any Apple formatted files once it ends its back to the drawing board? Thankyou in advance for any knowledge you may share
    Samuel

    My AppleTV 2 when I want to play media from my WinVistaPC 64bit iTunes 10.5 and my AppleTV also has up to date firmware when trying to play media from the "Computer" tab on the AppleTV my  PC and all of the media be it music ,movies or podcasts it tries to load  the spinning thing on the middle of the screen never loads then my PC disappears from the AppleTV and says "From your computer in iTunes login to Home Sharing with your AppleID " so I do that and IT STARTS WORKING! BUT! then after the media finishes playing it regresses back to the same problem and I have reinstalled iTunes and it doesnt resolve anything it says under the advanced tab of iTunes 10.5 that "Home Sharing is ON!" and I have to click "Turn off Home Sharing" then re enter my password again and restart the entire process only to have it let me play 1 media file of any Apple formatted files once it ends its back to the drawing board? Thankyou in advance for any knowledge you may share
    Samuel

  • My Ipod Video 30 GB isnt playing any songs any more, i can find them all but when i want to play one the player stops at 0:00, and i tried a reset and to formate it and so on but nohting seems to work, what can i do?

    My IPod Video 30 GB isn't playing any songs any more, i can find them all but when I want to play one the player stops at 0:00, and I tried a reset and to formatted it and so on but nothing seems to work, what can i do?

    Please helm me, has anyone got an idea?

  • Hi,i am using iphone 4s,my problem is when i want to play video other than youtube file from facebook this message come out "An error occured while processing your request. Reference

    Hi,i am using iphone 4s,my problem is when i want to play video other than youtube file from facebook this message come out "An error occured while processing your request. Reference

    Is your friends phone jailbroke? Also are you using the facebook app? If so then you need to ask the developer of the app what the problem is.

  • Itunes does not work when I want to play Mp4 videos with most recent versions

    When I want to play videos with mp4 format on itunes, it does not do anything and I have to close itunes with the windows system manager. Does any one know how to solve this problem? I did not have this isue with 10.5 and previous versions of itunes.

    I found the solution, the problem was the encoding of the configuration files.
    I put:
    => Encoding: UTF8 without signature
    => line endings: UNIX(LF)
    And now it works :)

  • I've downloaded movies from the iTunes store to my iPad but when I want to play them, I get the message... iTunes Store Terms and Conditions but when I follow the link it still doesn't let me play my movies. What am I doing wrong?

    I've downloaded movies from the iTunes store to my iPad but when I want to play them, I get the message... iTunes Store Terms and Conditions... but when I follow the link it still doesn't let me play my movies. What am I doing wrong?

    Easy maybe, but a lot of users are used to playing the movies in iTunes on their computers so that is the first place they turn to on the iPad.
    Enjoy the show!

  • I uploaded music in the match and when i want to play it in my phone, some of the tracks appear blocked (blanked) and a few not. When I'm connected through a wi fi spot, i can play all of the tracks. Help!

    I uploaded music in the match and when i want to play it in my phone, some of the tracks appear blocked (blanked) and a few not. When I'm connected in a wi fi spot, I can play all of the tracks. Help please.

    Hi,
    You need a wifi connection to stream. Previously played tracks appear in a temporary cache which allows them to be played again when yOu have no wifi..
    You can either predownload selected tracks or use cellular data.
    Jim

  • When we try to play a song on I tunes a ping runs through the play list and plays a random song

    When we try to play a song on I tunes a ping runs through the play list and plays a random song

    Nicky sh wrote:
    When we try to play a song on I tunes a ping runs through the play list
    What is "a ping"?
    Do all your songs have a check mark?

  • When I want to play a video, it asks me to download the latest Adobe Flash player, and the iPad won't do that.

    When I want to play a video, it asks me to download the latest Adobe Flash player, and the iPad won't do that.

    The iPad doesn't and never will support the Flash program. You will need to download and install a different browser like the aforementioned Skyfire. Photon and Puffin are also mentioned as browsers that support Flash. Or see if the place you're accessing that video from has an app.

Maybe you are looking for