Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Playing mp3 from variable
#1
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()
Reply
#2
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.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  pyAudio playing variable Talking2442 3 2,959 Dec-01-2020, 06:20 PM
Last Post: Talking2442

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020