99 lines
2.4 KiB
Lua
99 lines
2.4 KiB
Lua
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)) -- a–z
|
||
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 }
|