Add `speaker sound` command, better error message in `speaker play` if no arg given.

This commit is contained in:
Matthew W 2024-03-13 08:39:04 -06:00
parent 6fb291112d
commit 67c565ef02
No known key found for this signature in database
GPG Key ID: A2729491C5392E30
2 changed files with 43 additions and 2 deletions

View File

@ -45,6 +45,10 @@ elseif cmd == "play" then
local _, file, name = ...
local speaker = get_speakers(name)[1]
if not file then
error("Usage: speaker play <file or url> [speaker]", 0)
end
local handle, err
if http and file:match("^https?://") then
print("Downloading...")
@ -103,7 +107,7 @@ elseif cmd == "play" then
handle.read(4)
start = nil
-- Detect several other common audio files.
-- Detect several other common audio files.
elseif start == "OggS" then return report_invalid_format("Ogg")
elseif start == "fLaC" then return report_invalid_format("FLAC")
elseif start:sub(1, 3) == "ID3" then return report_invalid_format("MP3")
@ -128,9 +132,46 @@ elseif cmd == "play" then
end
handle.close()
elseif cmd == "sound" then
local _, sound, volume, pitch, name = ...
if not sound then
error("Usage: speaker sound <sound> [volume] [pitch] [speaker]", 0)
return
end
if volume then
volume = tonumber(volume)
if not volume then
error("Volume must be a number", 0)
end
if volume < 0 or volume > 3 then
error("Volume must be between 0 and 3", 0)
end
end
if pitch then
pitch = tonumber(pitch)
if not pitch then
error("Pitch must be a number", 0)
end
if pitch < 0 or pitch > 2 then
error("Pitch must be between 0 and 2", 0)
end
end
local speaker = get_speakers(name)[1]
if speaker.playSound(sound, volume, pitch) then
print(("Played sound %q on speaker %q with volume %s and pitch %s."):format(sound, peripheral.getName(speaker),
volume or 1, pitch or 1))
else
error(("Could not play sound %q"):format(sound), 0)
end
else
local programName = arg[0] or fs.getName(shell.getRunningProgram())
print("Usage:")
print(programName .. " play <file or url> [speaker]")
print(programName .. " sound <sound> [volume] [pitch] [speaker]")
print(programName .. " stop [speaker]")
end

View File

@ -117,7 +117,7 @@ shell.setCompletionFunction("rom/programs/fun/dj.lua", completion.build(
completion.peripheral
))
shell.setCompletionFunction("rom/programs/fun/speaker.lua", completion.build(
{ completion.choice, { "play ", "stop " } },
{ completion.choice, { "play ", "sound ", "stop " } },
function(shell, text, previous)
if previous[2] == "play" then return completion.file(shell, text, previous, true)
elseif previous[2] == "stop" then return completion.peripheral(shell, text, previous, false)