Class: DXOpal::Sound

Inherits:
RemoteResource show all
Defined in:
lib/dxopal/sound.rb

Direct Known Subclasses

SoundEffect

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from RemoteResource

[], _klass_name, _load_resources, _update_loading_status, add_class, register

Constructor Details

#initialize(path_or_url) ⇒ Sound

Returns a new instance of Sound.



36
37
38
# File 'lib/dxopal/sound.rb', line 36

def initialize(path_or_url)
  @path_or_url = path_or_url  # Used in error message
end

Instance Attribute Details

#decodedObject

Returns the value of attribute decoded.



39
40
41
# File 'lib/dxopal/sound.rb', line 39

def decoded
  @decoded
end

Class Method Details

._load(path_or_url) ⇒ Object

Load remote sound (called via Window.load_resources)



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/dxopal/sound.rb', line 15

def self._load(path_or_url)
  snd = new(path_or_url)
  snd_promise = %x{
    new Promise(function(resolve, reject) {
      var request = new XMLHttpRequest();
      request.open('GET', #{path_or_url}, true);
      request.responseType = 'arraybuffer';
      request.onload = function() {
        var audioData = request.response;
        var context = #{Sound.audio_context};
        context.decodeAudioData(audioData, function(decoded) {
          snd['$decoded='](decoded);
          resolve();
        });
      };
      request.send();
    });
  }
  return snd, snd_promise
end

.audio_contextObject

Return AudioContext



8
9
10
11
12
# File 'lib/dxopal/sound.rb', line 8

def self.audio_context
  @@audio_context ||= %x{
    new (window.AudioContext||window.webkitAudioContext)
  }
end

Instance Method Details

#play(loop_ = false) ⇒ Object

Play this sound



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/dxopal/sound.rb', line 42

def play(loop_ = false)
  raise "Sound #{path_or_url} is not loaded yet" unless @decoded
  source = nil
  %x{
    var context = #{Sound.audio_context};
    source = context.createBufferSource();
    source.buffer = #{@decoded};
    if (#{loop_}) {
      source.loop = true;
    }
    source.connect(context.destination);
    source.start(0); 
  }
  @source = source
end

#stopObject

Stop playing this sound (if playing)



59
60
61
62
63
# File 'lib/dxopal/sound.rb', line 59

def stop
  return unless @decoded 
  return unless @source
  @source.JS.stop()
end