Last active
March 18, 2025 22:08
-
-
Save Cheatoid/e798988c54b411e9d1b64e7aa7057d91 to your computer and use it in GitHub Desktop.
Simple DFPWM player for CC.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Simple DFPWM player for CC:T | |
-- https://gist.github.com/Cheatoid/e798988c54b411e9d1b64e7aa7057d91 | |
local dfpwm = require("cc.audio.dfpwm") | |
local CHUNK_SIZE = 16 * 1024 | |
local unpack = unpack or table.unpack | |
--- Play DFPWM audio from a file or URL | |
---@param path string Path (or direct URL) of the file to play | |
---@param speakers? table (Optional) List of speaker peripherals to play audio to | |
local function play_dfpwm(path, speakers) | |
assert(type(path) == "string", "bad argument #1 (string expected, got " .. type(path) .. ")") | |
assert(#path > 0, "path argument is empty") | |
speakers = speakers or { peripheral.find("speaker") } | |
assert(#speakers > 0, "speaker peripheral is missing") | |
local decoder = dfpwm.make_decoder() | |
local function playBuffer(buffer) | |
local players = {} | |
for i, speaker in next, speakers do | |
players[i] = function() | |
while not speaker.playAudio(buffer) do | |
os.pullEvent("speaker_audio_empty") | |
end | |
end | |
end | |
parallel.waitForAll(unpack(players)) | |
end | |
if path:lower():match("^https?:") then | |
assert(http and http.get, "http extension is disabled") | |
local request = assert(http.get(path, nil, true)) | |
path = assert(request.readAll(), "failed to read response") | |
request.close() | |
for i = 1, #path, CHUNK_SIZE do | |
playBuffer(decoder(path:sub(i, i + CHUNK_SIZE - 1))) | |
end | |
else | |
assert(fs.exists(path), "file path does not exist") | |
for chunk in io.lines(path, CHUNK_SIZE) do | |
playBuffer(decoder(chunk)) | |
end | |
end | |
end | |
local arg = ... | |
if arg then | |
play_dfpwm(arg) | |
end | |
return play_dfpwm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment