Python Forum

Full Version: Playing mp3 from variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Very much a beginner and just messing around having fun with Python. I'm working on a Raspberry Pi with Raspbian.

I put together the code below on Python 3. The song will not play when I put the bolded play_sound (seen below). However, if I replace the bolded play_sound with the actual song name, os.system('mpg123 -q song1.mp3 &') that song will play just fine just not when I replace that with the variable play_sound.

Can anyone nudge me in the right direction? The random.choice correctly chooses and prints a song from the list, but the next line won't play. Thank you in advance.

from gpiozero import LED, Button
import os
import random
led = LED(17)
btn = Button(4)
songs = ['song1.mp3', 'song2.mp3', 'song3.mp3']


while True:
    btn.wait_for_press()
    btn.wait_for_release()
    play_sound = random.choice(songs)
    print (play_sound)    [i]#so I know random.choice is working properly[/i]
    os.system('mpg123 -q  [b]play_sound[/b]  &')
    led.on()
    btn.wait_for_press()
    btn.wait_for_release()
    led.off()
That is not how you pass a  variable value to a system command. mpg123 is looking for file with name play_sound while the song has a name 'song1.mp3' for example.

os.system('mpg123 -q {}'.format(play_sound))
should work. I use mplayer or mpv

subprocess module offers more powerful tools to run system commands.
Thank you for the reply. That makes sense. Even though I have the song1.mp3 stored in the variable play_sound, mpg123 doesn't see it that way. It only sees play_sound. I will certainly try your code above when I get home from work. Why the curlies opposed to parenthesis?

Thank you again.