I have a working Python script that streams an internet radio station with Omxplayer. The script restarts Omxplayer if Omxplayer stops, such as when the internet signal is lost and reconnects. Restarting automatically is the whole point of the script.
‣ Is there a way to send the sound from Omxplayer to a USB card?
I don't think there is. [There is a way. See the answer below.] It doesn't affect Omxplayer to run
raspi-config and select USB Audio as the default. Omxplayer sends the sound to HDMI.
VLC can send sound to a USB card, but I couldn't make the script work with VLC. VLC stays open when the internet drops, but Omxplayer closes when the internet drops. Also,
player.is_playing() is true when VLC is open, even when VLC isn't playing anything.
‣ Is there a way to check whether VLC is idle, that is, open but not playing anything?
‣ Is there a different player that Python can easily check whether it's playing, like Omxplayer, and which sends sound to the USB card, like VLC?
Here is the working script with Omxplayer.
#!/usr/bin/env python3 from omxplayer.player import OMXPlayer from time import sleep STREAM = 'https://14523.live.streamtheworld.com/CLASSICALSTREAMAAC.aac' # Starts playing. player = OMXPlayer(STREAM) # Checks whether playing. while True: sleep(10) try: while player.is_playing(): sleep(10) else: sleep(10) # Tries to start playing again. except: try: player = OMXPlayer(STREAM) sleep(10) except: sleep(10)
To stop the music stream, press Ctrl+C twice. Or, if Terminal is closed, open Terminal and type
killall omxplayer.bin && killall python3.
Here is the nonworking script with VLC.
#!/usr/bin/env python3 import vlc import time STREAM = 'https://14523.live.streamtheworld.com/CLASSICALSTREAMAAC.aac' # Starts playing. player = vlc.MediaPlayer() media = vlc.Media(STREAM) player.set_media(media) player.play() # Checks whether playing, but doesn't work, # because is_playing returns True when VLC is open and idle. while True: time.sleep(10) try: while player.is_playing(): time.sleep(10) else: time.sleep(10) # Tries to start playing again. except: try: player.play() time.sleep(10) except: time.sleep(10)