summaryrefslogtreecommitdiff
path: root/sfx.lua
blob: c7e7377abbc2a6436b0793077b485aba103ffc21 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
local sfx = {}

sfx.sources = {}
sfx.volumes = {}
sfx.liquidActive = false

local LIQUID_FILTER = { type = "lowpass", volume = 0.8, highgain = 0.15 }

local MUSIC_SOURCES = {
    game_ambient_loop = true,
    UI_loop_song = true,
}

local DEFAULT_VOLUMES = {
    game_ambient_loop = 0.3,
    UI_loop_song = 0.5,
    running = 0.35,
    die = 0.7,
    dive = 0.6,
    jump = 0.5,
    land = 0.5,
    HUD = 0.5,
    pickup = 0.5,
    UI = 0.5,
}

function sfx.load()
    local dir = "assets/sfx"
    local ok, items = pcall(love.filesystem.getDirectoryItems, dir)
    if not ok or not items then return end

    for _, filename in ipairs(items) do
        local ext = filename:match("%.(%w+)$")
        if ext == "ogg" or ext == "mp3" or ext == "wav" then
            local name = filename:gsub("%.[^.]+$", "")
            local sourceType = MUSIC_SOURCES[name] and "stream" or "static"
            local success, src = pcall(love.audio.newSource, dir .. "/" .. filename, sourceType)
            if success and src then
                local vol = DEFAULT_VOLUMES[name] or 0.5
                src:setVolume(vol)
                sfx.sources[name] = src
                sfx.volumes[name] = vol
            end
        end
    end
end

function sfx.play(name)
    local src = sfx.sources[name]
    if not src then return end
    src:stop()
    src:setLooping(false)
    if sfx.liquidActive and not MUSIC_SOURCES[name] then
        pcall(src.setFilter, src, LIQUID_FILTER)
    end
    src:play()
end

function sfx.loop(name)
    local src = sfx.sources[name]
    if not src then return end
    if src:isPlaying() then return end
    src:setLooping(true)
    src:play()
end

function sfx.stop(name)
    local src = sfx.sources[name]
    if not src then return end
    src:stop()
end

function sfx.isPlaying(name)
    local src = sfx.sources[name]
    return src and src:isPlaying()
end

function sfx.setVolume(name, vol)
    local src = sfx.sources[name]
    if not src then return end
    sfx.volumes[name] = vol
    src:setVolume(vol)
end

function sfx.setLiquidEffect(active)
    if sfx.liquidActive == active then return end
    sfx.liquidActive = active
    for name, src in pairs(sfx.sources) do
        if not MUSIC_SOURCES[name] then
            if active then
                pcall(src.setFilter, src, LIQUID_FILTER)
            else
                pcall(src.setFilter, src)
            end
        end
    end
end

function sfx.stopAll()
    for _, src in pairs(sfx.sources) do
        src:stop()
    end
end

return sfx