I have a code with which I want my Raspberry Pi to play a certain set of music playlist from a folder.

        if top_mood==mood_happy:
            print "the mood is: happy"

        elif top_mood==mood_sad:
            print "the mood is:sad"

        elif top_mood==mood_angry:
            print "the mood is:angry"

        elif top_mood==mood_shocked:
            print "the mood is: shocked"

        elif top_mood==mood_romantic:
            print "the mood is: romantic"

As you can see, for each variable "mood_n" I have created a separate folder containing mp3 files. I want Raspberry Pi to play music from the folder 'n' when a particular mood_n is printed.

I've heard of Pygame and other such libraries so I wanted to know which would be the best way?


Pygame can be used to play music.

See Making Games With Pygame (.pdf)

For a simple example:

# libraries
import pygame
import time

# instantiate pygame

# select track
pygame.mixer.music.load("./directory/01 Track name.mp3")

# play music (on loop)
pygame.mixer.music.play(-1, 0.0)

# wait

# stop music

Looking at your code above, you'll probably want to select the tracks inside the decision structure, and play the track outside of this structure.

Something like this:

# libraries
import pygame

# instantiate pygame

# set mood
mood_happy = 0.2
mood_sad = 0.3
mood_angry = 0.2
mood_shocked = 0.2
mood_romantic = 0.1

# find top mood
top_mood = max(mood_happy,

# select track
if top_mood == mood_happy:
    print "the mood is: happy"
    # select happy track
    pygame.mixer.music.load("./directory/01 Happy Track Name.mp3")

elif top_mood == mood_sad:
    print "the mood is:sad"
    # select sad track
    pygame.mixer.music.load("./directory/02 Sad Track Name.mp3")

elif top_mood == mood_angry:
    print "the mood is:angry"
    # select angry track
    pygame.mixer.music.load("./directory/03 Angry Track Name.mp3")

elif top_mood == mood_shocked:
    print "the mood is: shocked"
    # select shocked track
    pygame.mixer.music.load("./directory/04 Shocked Track Name.mp3")

elif top_mood == mood_romantic:
    print "the mood is: romantic"
    # select romantic track
    pygame.mixer.music.load("./directory/05 Romantic Track Name.mp3")

# play music track
pygame.mixer.music.play(1, 0.0)
  • 1
    Some further explanation might be nice.. – Darth Vader May 19 '17 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy