/lib/chingu/gosu_ext/sample.rb

http://github.com/ippa/chingu · Ruby · 79 lines · 57 code · 15 blank · 7 comment · 2 complexity · e52f2b10d6188faf1d98131ae214402c MD5 · raw file

  1. module Gosu
  2. class Sample
  3. DEFAULT_VOLUME = 1.0 # Default volume of new samples.
  4. class << self
  5. # Volume of all Samples.
  6. attr_reader :volume
  7. public
  8. # Volume of Samples, affected by Sample.volume and Window#volume and muting.
  9. def effective_volume
  10. @volume * $window.effective_volume
  11. end
  12. public
  13. # Set the global volume of Samples.
  14. def volume=(value)
  15. raise "Bad volume setting" unless value.is_a? Numeric
  16. @volume = [[value, 1.0].min, 0.0].max.to_f
  17. end
  18. public
  19. def init_sound
  20. @volume = DEFAULT_VOLUME
  21. nil
  22. end
  23. end
  24. init_sound
  25. # Volume of this Sample. This is multiplied by the volume in #play.
  26. attr_reader :volume
  27. alias_method :old_initialize, :initialize
  28. protected :old_initialize
  29. public
  30. # Accepts :volume (0.0..1.0) option, defaulting to 1.0.
  31. def initialize(filename, options = {})
  32. options = {
  33. volume: DEFAULT_VOLUME,
  34. }.merge! options
  35. @volume = options[:volume]
  36. old_initialize(filename)
  37. end
  38. public
  39. # Set the volume of this Sample. This is multiplied by the volume in #play.
  40. def volume=(value)
  41. raise "Bad volume setting" unless value.is_a? Numeric
  42. @volume = [[value, 1.0].min, 0.0].max.to_f
  43. end
  44. public
  45. # Volume the Sample will actually be played at, affected by Sample.volume and Window#volume.
  46. def effective_volume
  47. @volume * self.class.effective_volume
  48. end
  49. alias_method :old_play, :play
  50. protected :old_play
  51. public
  52. def play(volume = 1, speed = 1, looping = false)
  53. volume *= effective_volume
  54. old_play(volume, speed, looping) if volume > 0.0
  55. end
  56. alias_method :old_play_pan, :play_pan
  57. protected :old_play_pan
  58. public
  59. def play_pan(pan = 0, volume = 1, speed = 1, looping = false)
  60. volume *= effective_volume
  61. old_play_pan(pan, volume, speed, looping) if volume > 0.0
  62. end
  63. end
  64. end