Initial commit of BGMusic
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
import gi # type: ignore
|
||||
gi.require_version('Gst','1.0')
|
||||
from gi.repository import Gst # type: ignore
|
||||
import sys
|
||||
import select
|
||||
import time
|
||||
import os
|
||||
import paho.mqtt.client as mqtt # type: ignore
|
||||
import re
|
||||
|
||||
Gst.init(None)
|
||||
|
||||
mqtt = mqtt.Client()
|
||||
mqtt.connect("10.40.0.2", 1883)
|
||||
|
||||
def play_song(Song_path):
|
||||
#GStreamer Player
|
||||
pipeline = Gst.parse_launch(
|
||||
f'filesrc location="{Song_path}" ! \
|
||||
mpegaudioparse ! avdec_mp3 ! \
|
||||
queue ! audioconvert ! \
|
||||
queue ! audioresample ! \
|
||||
audio/x-raw,rate=44100,channels=2 ! \
|
||||
rtpL16pay ! \
|
||||
udpsink host=10.40.0.100 port=5004 '
|
||||
)
|
||||
|
||||
pipeline.set_state(Gst.State.PLAYING)
|
||||
|
||||
title = os.path.basename(Song_path)
|
||||
title = os.path.splitext(title)[0]
|
||||
title = re.sub(r'\s*\[[^\]]+\]$', '', title)
|
||||
print("🎵 Now Playing:", title)
|
||||
mqtt.publish("player/current", title)
|
||||
|
||||
bus = pipeline.get_bus()
|
||||
print("Press 'q' then Enter to stop early.")
|
||||
|
||||
user_input = ""
|
||||
status = "unknown"
|
||||
|
||||
while True:
|
||||
# Check for messages from GStreamer
|
||||
msg = bus.timed_pop_filtered(0, Gst.MessageType.ERROR | Gst.MessageType.EOS)
|
||||
if msg:
|
||||
if msg.type == Gst.MessageType.EOS:
|
||||
print("✅ Song finished.")
|
||||
break
|
||||
elif msg.type == Gst.MessageType.ERROR:
|
||||
err, debug = msg.parse_error()
|
||||
print("❌ Error:", err)
|
||||
status = "error"
|
||||
break
|
||||
|
||||
# Check if user typed "q"
|
||||
user_input = None
|
||||
|
||||
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
|
||||
user_input = sys.stdin.readline().strip()
|
||||
if user_input:
|
||||
command = user_input.lower()
|
||||
|
||||
if command == "q":
|
||||
print("🛑 Quitting early.")
|
||||
status = "quit"
|
||||
break
|
||||
|
||||
elif command == "skip":
|
||||
print("⏩ Skipping song from controller.")
|
||||
status = "skip"
|
||||
break
|
||||
|
||||
#elif command == "pause":
|
||||
#print("⏸ Pausing playback.") NOTE: Left in for the "Just in case" scenario.
|
||||
#pipeline.set_state(Gst.State.PAUSED) NOTE: Audio "pausing" is handled by AHM fading to 0%
|
||||
|
||||
#elif command == "play":
|
||||
#print("▶️ Resuming playback.") NOTE: Left in for the "Just in case" scenario.
|
||||
#pipeline.set_state(Gst.State.PLAYING) NOTE: Audio "pausing" is handled by AHM fading to 0%
|
||||
|
||||
time.sleep(0.1)
|
||||
|
||||
if not status or status == "unknown":
|
||||
status = "Finished"
|
||||
|
||||
pipeline.set_state(Gst.State.NULL)
|
||||
pipeline.get_state(Gst.CLOCK_TIME_NONE)
|
||||
del pipeline
|
||||
return status
|
||||
Reference in New Issue
Block a user