sound.lua 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. Sound = class()
  2. function Sound:init(options)
  3. options = options or {}
  4. self.muted = options.muted or false
  5. self.volumes = {master = options.master or 1.0, music = options.music or 1.0, sound = options.sound or 1.0}
  6. self.sounds = {}
  7. self.tags = {sound = setmetatable({}, {__mode = 'kv'}), music = setmetatable({}, {__mode = 'kv'})}
  8. self.baseVolumes = setmetatable({}, {__mode = 'k'})
  9. if ctx.event then
  10. ctx.event:on('sound.play', f.cur(self.play, self))
  11. ctx.event:on('sound.loop', f.cur(self.loop, self))
  12. end
  13. end
  14. function Sound:update()
  15. love.audio.setPosition(ctx.view.x + ctx.view.width / 2, ctx.view.y + ctx.view.height / 2, 200)
  16. end
  17. function Sound:play(sound, cb)
  18. if self.muted or not sound then return end
  19. if type(sound) == 'string' then sound = data.media.sounds[sound] end
  20. if not sound then return end
  21. local isMusic = self:isMusic(sound)
  22. local sound = sound:play()
  23. if sound then f.exe(cb, sound) end
  24. local tag = isMusic and 'music' or 'sound'
  25. self.tags[tag] = self.tags[tag] or {}
  26. self.tags[tag][sound] = sound
  27. self.baseVolumes[sound] = sound:getVolume()
  28. self:refreshVolumes()
  29. return sound
  30. end
  31. function Sound:loop(sound, cb)
  32. return self:play(sound, function(sound)
  33. sound:setLooping(true)
  34. f.exe(cb, sound)
  35. end)
  36. end
  37. function Sound:mute()
  38. self.muted = not self.muted
  39. self:refreshVolumes()
  40. end
  41. function Sound:setMute(muted)
  42. if self.muted ~= muted then self:mute() end
  43. end
  44. function Sound:isMusic(sound)
  45. return sound == data.media.sounds.riteOfPassage or (ctx.biome and sound == data.media.sounds[ctx.biome])
  46. end
  47. function Sound:refreshVolumes()
  48. table.each(self.tags.music, function(sound)
  49. sound:setVolume(self.muted and 0 or self.volumes.master * self.volumes.music * (self.baseVolumes[sound] or 1))
  50. end)
  51. table.each(self.tags.sound, function(sound)
  52. sound:setVolume(self.muted and 0 or self.volumes.master * self.volumes.sound * (self.baseVolumes[sound] or 1))
  53. end)
  54. end