Playing mp3 from variable - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Playing mp3 from variable (/thread-4632.html) |
Playing mp3 from variable - mstone326 - Aug-31-2017 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() RE: Playing mp3 from variable - wavic - Aug-31-2017 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. RE: Playing mp3 from variable - mstone326 - Aug-31-2017 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. |