| | | @@ -0,0 +1,75 @@ |
| 1 | + | local CODE = 107 |
| 2 | + | |
| 3 | + | local soundChannels = {} |
| 4 | + | local maxChannels = 70 |
| 5 | + | local channelTimers = {} |
| 6 | + | |
| 7 | + | |
| 8 | + | for i = 1, maxChannels do |
| 9 | + | local channel = g_sounds.getChannel(SoundChannels["Spells" .. i]) |
| 10 | + | if channel then |
| 11 | + | soundChannels[i] = channel |
| 12 | + | else |
| 13 | + | print("Failed to initialize sound channel " .. i) |
| 14 | + | end |
| 15 | + | end |
| 16 | + | |
| 17 | + | function onExtendedOpcode(protocol, code, buffer) |
| 18 | + | |
| 19 | + | local json_status, json_data = pcall(function() |
| 20 | + | return json.decode(buffer) |
| 21 | + | end) |
| 22 | + | |
| 23 | + | if not json_status then |
| 24 | + | print("Error decoding JSON: " .. json_data) |
| 25 | + | return false |
| 26 | + | end |
| 27 | + | |
| 28 | + | local action = json_data.action |
| 29 | + | local soundFile = json_data.data |
| 30 | + | |
| 31 | + | local soundFilePath = "sounds/" .. soundFile |
| 32 | + | |
| 33 | + | if g_resources.fileExists(soundFilePath) then |
| 34 | + | playSound(soundFilePath) |
| 35 | + | else |
| 36 | + | print("Sound file does not exist: " .. soundFilePath) |
| 37 | + | end |
| 38 | + | end |
| 39 | + | |
| 40 | + | function playSound(sound) |
| 41 | + | local channel = findAvailableChannel() |
| 42 | + | if not channel then |
| 43 | + | print("No available sound channels.") |
| 44 | + | return |
| 45 | + | end |
| 46 | + | |
| 47 | + | channel:play(sound, 0, 1.0) |
| 48 | + | channel:setGain(1.0) |
| 49 | + | |
| 50 | + | local duration = getSoundDuration(sound) or 3000 |
| 51 | + | channelTimers[channel] = scheduleEvent(function() |
| 52 | + | channelTimers[channel] = nil |
| 53 | + | end, duration) |
| 54 | + | end |
| 55 | + | |
| 56 | + | function findAvailableChannel() |
| 57 | + | for _, channel in ipairs(soundChannels) do |
| 58 | + | if not channelTimers[channel] then |
| 59 | + | return channel |
| 60 | + | end |
| 61 | + | end |
| 62 | + | return nil |
| 63 | + | end |
| 64 | + | |
| 65 | + | function getSoundDuration(sound) |
| 66 | + | return 3000 |
| 67 | + | end |
| 68 | + | |
| 69 | + | function init() |
| 70 | + | ProtocolGame.registerExtendedOpcode(CODE, onExtendedOpcode) |
| 71 | + | end |
| 72 | + | |
| 73 | + | function terminate() |
| 74 | + | ProtocolGame.unregisterExtendedOpcode(CODE) |
| 75 | + | end |