soundloop.lua 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. local soundloop = {}
  2. local sounds = {}
  3. local function parse_sound(sound)
  4. if type(sound) == "string" then
  5. return { name = sound, gain = 1, pitch = 1 }
  6. end
  7. if sound.gain == nil then sound.gain = 1 end
  8. if sound.pitch == nil then sound.pitch = 1 end
  9. return sound
  10. end
  11. soundloop.play = function(player, sound, fade)
  12. sound = parse_sound(sound)
  13. if fade == nil then fade = 1 end
  14. local step
  15. local handle
  16. local start_gain
  17. if sounds[player] == nil then sounds[player] = {} end
  18. if sounds[player][sound.name] == nil then
  19. step = sound.gain / fade
  20. start_gain = 0
  21. elseif sounds[player][sound.name] ~= sound.gain then
  22. minetest.sound_stop(sounds[player][sound.name].handle)
  23. start_gain = sounds[player][sound.name].gain
  24. local change = sound.gain - start_gain
  25. step = change / fade
  26. else
  27. return
  28. end
  29. handle = minetest.sound_play(sound.name, {
  30. to_player = player,
  31. loop = true,
  32. gain = 0
  33. })
  34. sounds[player][sound.name] = {
  35. gain = sound.gain,
  36. handle = handle
  37. }
  38. minetest.sound_fade(handle, step, sound.gain)
  39. return handle
  40. end
  41. soundloop.stop = function(player, sound, fade)
  42. sound = parse_sound(sound)
  43. if sounds[player] == nil or sounds[player][sound.name] == nil then
  44. return
  45. end
  46. if fade == nil then fade = 1 end
  47. local handle = sounds[player][sound.name].handle
  48. local step = -sounds[player][sound.name].gain / fade
  49. minetest.sound_fade(handle, step, 0)
  50. sounds[player][sound.name].gain = 0
  51. minetest.after(fade, minetest.sound_stop, handle)
  52. end
  53. return soundloop