Files
nova-corp/speaker-driver.lua
2025-12-13 20:13:54 -05:00

99 lines
2.4 KiB
Lua
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
local speaker = peripheral.find("speaker")
local dfpwm = require("cc.audio.dfpwm")
local encoder = dfpwm.make_encoder()
local decoder = dfpwm.make_decoder()
local sounds = {
{name = "notification", file = "notification.dfpwm"}
}
local function initialize()
kernel = require("kernel")
kernel.addSound("notification")
speaker = peripheral.find("speaker")
if not speaker then
print("Warning: No speaker attached.")
return false
end
return true
end
local function play(name)
if not speaker then return false end
local filePath
for _, sound in ipairs(sounds) do
if sound.name == name then
filePath = sound.file
break
end
end
if not filePath then
print("Sound '" .. name .. "' not defined.")
return false
end
if not fs.exists(filePath) then
print("File '" .. filePath .. "' not found.")
return false
end
-- Create a new decoder for this playback to reset state
local decoder = dfpwm.make_decoder()
for chunk in io.lines(filePath, 16 * 1024) do
local buffer = decoder(chunk)
while not speaker.playAudio(buffer, 3.0) do
os.pullEvent("speaker_audio_empty")
end
end
return true
end
----------------
local function getFileName(name)
local extension = ".dfpwm"
local fullFile = name .. extension
return fullFile
end
local function randomFileName()
local name = ""
for i = 1, 12 do
name = name .. string.char(math.random(97, 122)) -- az
end
return name
end
local function playSound(fileName)
local fileStream = getFileName(fileName)
local values = io.lines(fileStream, 16 * 1024)
for input in values do
local decoded = decoder(input)
while not speaker.playAudio(decoded, 3.0) do
os.pullEvent("speaker_audio_empty")
end
end
end
local function playTTSFile(value)
local message = textutils.urlEncode(value)
local url = "http://api.astrocore.space/api/TextToSpeech?message=" .. message
local response, err = http.get { url = url, binary = true }
local name = randomFileName()
local fileName = name .. ".dfpwm"
local fileData = response.readAll()
local file = fs.open(fileName,"w")
file.write(fileData)
file.close()
response.close()
playSound(name)
shell.execute("rm", fileName)
end
return { initialize = initialize, play = play, playTTSFile = playTTSFile }