Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local streamURL = "https://server.radio/stream.dfpwm"
- local speakerList = {}
- local playing = false
- local volume = 1.0
- local dfpwm = require("cc.audio.dfpwm")
- local decoder = dfpwm.make_decoder()
- local function findSpeakers()
- speakerList = {}
- for _, side in ipairs(peripheral.getNames()) do
- if peripheral.getType(side) == "speaker" then
- table.insert(speakerList, peripheral.wrap(side))
- end
- end
- end
- -- Draw
- local function drawUI()
- term.clear()
- term.setCursorPos(1,1)
- print("== radio")
- print("Status: " .. (playing and "Playing" or "Paused"))
- print("Volume: " .. math.floor(volume * 100) .. "%")
- print("")
- print("[P] Play/Pause")
- print("[+] Volume Up")
- print("[-] Volume Down")
- print("[Q] Quit")
- end
- local function playStream()
- http.request(streamURL)
- end
- -- Stream audio
- local function streamLoop()
- while true do
- local event, url, handle = os.pullEvent()
- if event == "http_success" then
- local response = handle
- while playing do
- local chunk = response.read(16 * 1024)
- if not chunk then break end
- local sound = decoder(chunk)
- for _, speaker in ipairs(speakerList) do
- if speaker and speaker.playAudio then
- while not speaker.playAudio(sound, volume) do
- os.pullEvent("speaker_audio_empty")
- end
- end
- end
- end
- response.close()
- elseif event == "http_failure" then
- print("Failed to connect to stream.")
- end
- end
- end
- -- Input
- local function controlLoop()
- drawUI()
- while true do
- local key = read()
- if key == "p" then
- playing = not playing
- drawUI()
- if playing then
- playStream()
- end
- elseif key == "+" then
- volume = math.min(1.0, volume + 0.1)
- drawUI()
- elseif key == "-" then
- volume = math.max(0.1, volume - 0.1)
- drawUI()
- elseif key == "q" then
- os.shutdown()
- end
- end
- end
- findSpeakers()
- parallel.waitForAny(streamLoop, controlLoop)
Advertisement
Add Comment
Please, Sign In to add comment