Wikia

Music Player Daemon Community Wiki

Hack:ralbumd

525pages on
this wiki
Talk0

Simple C daemon that polls mpd and plays a random album when the current playlist is finished. libmpd is required to compile, make sure you tell gcc to use it with -lmpd. There's probably a better way to detect the end of the current playlist, but this works for me.

  • Source
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <libmpd/libmpd.h>

#define TRUE 1
#define FALSE 0

void playAlbum(MpdObj *mo, char* album);

int main(int argc, char **argv)
{
   pid_t pid, sid;

   pid = fork();

   if (pid < 0) {
       exit(1);
   } else if (pid > 0) {
       exit(0);
   }

   umask(0);
   sid = setsid();

   if (sid < 0) {
       exit(1);
   }

   if ((chdir("/")) < 0) {
       exit(1);
   }
    
   int playlist_end, random, count;   
   
	MpdObj *mo;
   MpdData *albums = NULL;

	mo = mpd_new_default();
	srand(time(NULL));

	if(mpd_connect(mo))
	{
		mpd_free(mo);
		printf("Failed to connect to mpd\n");
		exit(1);
	}
   
   while(1)
	{
	   if( playlist_end )
	   {
   	   if(mpd_player_get_state(mo) == MPD_PLAYER_STOP)
	      {
         	random = (int)(rand() % mpd_stats_get_total_albums(mo) );
         	
         	albums = mpd_database_get_albums(mo, NULL);
         	for(count = 0; count < random; count++)
            {
               albums = mpd_data_get_next(albums);
            }

         	playAlbum(mo, albums->tag);
            mpd_data_free(albums);
	      }
	   
	   }
	   	   
	   if( mpd_status_get_total_song_time(mo) - mpd_status_get_elapsed_song_time(mo) < 3 
	      && (mpd_playlist_get_playlist_length(mo) - mpd_player_get_current_song_pos(mo)) == 1 )
	   {
	      playlist_end = TRUE;
	   }
	   else
	   {
	      playlist_end = FALSE;
	   }
	   
	   mpd_status_update(mo);
	   usleep(500000);
	}
	
	mpd_free(mo);
	exit(0);
}

void playAlbum(MpdObj *mo, char* album)
{
	mpd_playlist_clear(mo);
			
	MpdData *data = mpd_database_find(mo, MPD_TABLE_ALBUM, album, TRUE);
	while (data != NULL)
	{
		if(data->type == MPD_DATA_TYPE_SONG)
		{
			mpd_playlist_queue_add(mo,data->song->file);
		}
		data = mpd_data_get_next(data);
	}
   mpd_data_free(data);
	mpd_playlist_queue_commit(mo);
	mpd_player_play(mo);
}

Around Wikia's network

Random Wiki