Skip to content

Instantly share code, notes, and snippets.

@Cheatoid
Last active November 4, 2023 21:56
Show Gist options
  • Save Cheatoid/e798988c54b411e9d1b64e7aa7057d91 to your computer and use it in GitHub Desktop.
Save Cheatoid/e798988c54b411e9d1b64e7aa7057d91 to your computer and use it in GitHub Desktop.
Simple DFPWM player for CC.
-- 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