Not logged inGosu Forums
Forum back to libgosu.org Help Search Register Login
Up Topic Gosu / Gosu Exchange / Is an Audio cache/manager a good idea?
- - By Omegas7 Date 2012-05-13 15:55
I am new with gosu and decided to make a class to handle my audio playing needs. I ended up with this:

require 'rubygems'
require 'gosu'

class Audio
  def initialize(source)
    @source = source   # The game window
    @bgm = {}
    @se = {}
    loadBGM
    loadSE
  end
 
  def playBGM(file)
    @bgm[file].play
  end
 
  def playSE(file)
    @se[file].play
  end
 
  def loadBGM
    Dir.glob(File.join(File.dirname(__FILE__), 'Audio/BGM/') + '*.wav') do |wav_file|
      @bgm[File.basename(wav_file)] = Gosu::Song.new(@source,wav_file)
    end
  end
 
  def loadSE
    Dir.glob(File.join(File.dirname(__FILE__), 'Audio/SE/') + '*.wav') do |wav_file|
      @se[File.basename(wav_file)] = Gosu::Sample.new(@source,wav_file)
    end
  end
end


So far, it does work. But what do you think? Was it even a good idea to load all audio at once in this class?

And also, I almost do the same thing with Images. I load all images in my graphics folder at once the same way I do with audio. Was that okay as well?
Parent - - By erisdiscord Date 2012-05-13 21:38
Some kind of resource manager is always a good idea for a project of any size. I wouldn't personally load every song and sound effect at the beginning, though, unless there are only a few of them.

I might have implemented something like this:

class Audio
  AUDIO_PATH = File.join(File.dirname(__FILE__), 'Audio')
  BGM_PATH   = File.join(AUDIO_PATH, 'BGM')
  SE_PATH    = File.join(AUDIO_PATH, 'SE')
 
  def initialize(source)
    @source = source   # The game window
    @bgm = {}
    @se = {}
  end
 
  # Clear preloaded audio resources.
  def clear
    @bgm.clear
    @se.clear
  end
 
  # Preload the BGM +file+.
  def preloadBGM(file)
    @bgm[file] ||= File.join(BGM_PATH, "#{file}.wav")
  end
 
  # Preload the sound effect +name+.
  def preloadSE(file)
    @se[file] ||= File.join(SE_PATH, "#{file}.wav")
  end
 
  # Play the BGM +file+. If +file+ hasn't been preloaded, it will be loaded
  # on demand the first time it's played.
  def playBGM(file)
    preloadBGM(file).play
  end
 
  # Play the sound effect +file+. If +file+ hasn't been preloaded, it will be
  # loaded on demand the first time it's played.
  def playSE(file)
    preloadSE(file).play
  end
 
end


Call clear at the end of a level, scene change or whatever, then preload any files that you anticipate using.
Parent - - By Omegas7 Date 2012-05-14 02:01
I see, thanks. So the same goes for Images?
Parent - By erisdiscord Date 2012-05-14 02:04
Well, that's my advice, but it's up to you to decide what you think is right for your game. Don't let me tell you what to do if you don't agree. :Ɔ
Up Topic Gosu / Gosu Exchange / Is an Audio cache/manager a good idea?

Powered by mwForum 2.29.7 © 1999-2015 Markus Wichitill