1 | extends Spatial
|
---|
2 |
|
---|
3 | # The audio player node.
|
---|
4 | var audio_node = null
|
---|
5 | # A variable to track whether or not we should loop
|
---|
6 | var should_loop = false
|
---|
7 | # The globals autoload script
|
---|
8 | var globals = null
|
---|
9 |
|
---|
10 | func _ready():
|
---|
11 | # Get the audio player node, connect the finished signal, and assure it's not playing anything.
|
---|
12 | audio_node = $Audio_Stream_Player
|
---|
13 | audio_node.connect("finished", self, "sound_finished")
|
---|
14 | audio_node.stop()
|
---|
15 |
|
---|
16 | # Get the globals script
|
---|
17 | globals = get_node("/root/Globals")
|
---|
18 |
|
---|
19 |
|
---|
20 | func play_sound(audio_stream, position=null):
|
---|
21 | # Based on the passed in sound, set the audio stream and then play it.
|
---|
22 | # If we do not have an sound stream with that name, then simply destroy ourselves.
|
---|
23 | #
|
---|
24 | # This is not included in the tutorial, but is here because you have to provide your
|
---|
25 | # own audio. To make the project work, we add this check.
|
---|
26 | if audio_stream == null:
|
---|
27 | print ("No audio stream passed, cannot play sound")
|
---|
28 | globals.created_audio.remove(globals.created_audio.find(self))
|
---|
29 | queue_free()
|
---|
30 | return
|
---|
31 |
|
---|
32 | # Set the audio stream to the passed in audio stream
|
---|
33 | audio_node.stream = audio_stream
|
---|
34 |
|
---|
35 | # If you are using a AudioPlayer3D, then uncomment these lines to set the position.
|
---|
36 | # if position != null:
|
---|
37 | # audio_node.global_transform.origin = position
|
---|
38 |
|
---|
39 | # Play the sound from the beginning
|
---|
40 | audio_node.play(0.0)
|
---|
41 |
|
---|
42 |
|
---|
43 | func sound_finished():
|
---|
44 | if should_loop:
|
---|
45 | # Start playing again, at the beginning
|
---|
46 | audio_node.play(0.0)
|
---|
47 | else:
|
---|
48 | # Destroy/Free this sound.
|
---|
49 | globals.created_audio.remove(globals.created_audio.find(self))
|
---|
50 | audio_node.stop()
|
---|
51 | queue_free()
|
---|