代码如下:
import sys
import subprocess
import threading
import time
import os
# Radio Stations List
STATIONS = [
{'id': 1, 'name': '内蒙古新闻广播 (Nei Menggu News)', 'url': '
http://lhttp.qtfm.cn/live/1883/64k.mp3'},
{'id': 2, 'name': '云南新闻广播 (Yunnan News)', 'url': '
http://lhttp.qtfm.cn/live/1926/64k.mp3'},
{'id': 3, 'name': '经典 80 年代 (China 80s)', 'url': '
http://lhttp.qtfm.cn/live/20207/64k.mp3'},
{'id': 4, 'name': 'SAW 80s (International)', 'url': '
http://stream.saw-musikwelt.de/saw-80er/mp3-128/'},
]
current_process = None
current_station_id = 1
def clear_screen():
os.system('cls' if
os.name == 'nt' else 'clear')
def play_station(station):
global current_process
# Stop existing process if any
if current_process:
try:
current_process.terminate()
current_process.wait(timeout=1)
except:
try:
current_process.kill()
except:
pass
# Start new process
# -nodisp: no graphical window
# -autoexit: exit when stream ends (though streams usually don't end)
# -loglevel quiet: suppress output
cmd = ['ffplay', '-nodisp', '-autoexit', '-loglevel', 'quiet', station['url']]
try:
current_process = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except FileNotFoundError:
print("Error: ffplay not found. Please install ffmpeg.")
sys.exit(1)
def print_ui():
clear_screen()
print("=== CLI FM Radio ===")
print("Enter station ID to switch. Ctrl+C to exit.\n")
for station in STATIONS:
if station['id'] == current_station_id:
# Red color for active station
print(f"\033[91m[{station['id']}] {station['name']} (Playing)\033[0m")
else:
print(f"[{station['id']}] {station['name']}")
print("\n> ", end='', flush=True)
def main():
global current_station_id
# Play default station (first one)
play_station(STATIONS[0])
print_ui()
try:
while True:
try:
user_input = input()
if not user_input.strip():
print_ui()
continue
new_id = int(user_input.strip())
found = False
for station in STATIONS:
if station['id'] == new_id:
current_station_id = new_id
play_station(station)
found = True
break
if not found:
# Just refresh UI if invalid input
pass
print_ui()
except ValueError:
print_ui()
except KeyboardInterrupt:
print("\nExiting...")
if current_process:
current_process.terminate()
sys.exit(0)
if __name__ == "__main__":
main()