@@ -16,19 +16,58 @@ signal soundEvent(soundName: String, id: int, playedAt: float)
16
16
17
17
var lastId = - 1
18
18
19
+ #region Public API
20
+ ## Reset the AudioEventPlayer. Makes sure that all events will be played
21
+ ## when starting again.
22
+ func reset ():
23
+ lastId = - 1
24
+
25
+
26
+ func play ():
27
+ if not _precondition ("Cannot call play()" ):
28
+ return
29
+
30
+ # Resume if it was paused
31
+ if audioStreamPlayer .stream_paused :
32
+ audioStreamPlayer .stream_paused = false
33
+ return
34
+
35
+ # Else reset and start again
36
+ reset ()
37
+ audioStreamPlayer .stream = audioEventStream .audio
38
+ audioStreamPlayer .play ()
39
+
40
+ func pause ():
41
+ if not _precondition ("Cannot call pause()" ):
42
+ return
43
+
44
+ if audioStreamPlayer .playing :
45
+ audioStreamPlayer .stream_paused = true
46
+
47
+ func stop ():
48
+ if not _precondition ("Cannot call stop()" ):
49
+ return
50
+ reset ()
51
+ audioStreamPlayer .stop ()
52
+
53
+ #endregion
54
+
55
+ #region Godot callbacks
19
56
func _ready ():
20
- var p = get_parent ()
21
- if p is AudioStreamPlayer :
22
- audioStreamPlayer = p
57
+ if audioStreamPlayer == null :
58
+ var p = get_parent ()
59
+ if p is AudioStreamPlayer :
60
+ audioStreamPlayer = p
23
61
if audioStreamPlayer == null :
24
62
push_error ("Please assign AudioStreamPlayer, or make sure the parent is one!" )
25
63
assert (false )
26
-
64
+
65
+ audioStreamPlayer .finished .connect (reset )
66
+
27
67
if audioEventStream :
28
68
audioStreamPlayer .stream = audioEventStream .audio
29
- if audioStreamPlayer .autoplay :
69
+ if audioStreamPlayer .autoplay and not audioStreamPlayer . playing :
30
70
audioStreamPlayer .play ()
31
-
32
71
33
72
func _process (_delta ):
34
73
if not audioStreamPlayer or not audioEventStream :
@@ -37,6 +76,12 @@ func _process(_delta):
37
76
if ! audioStreamPlayer .playing :
38
77
return
39
78
79
+ # Make sure to only call events from this AudioEventPlayer
80
+ # in case multiple AudioEventStreams are using a single AudioStreamPlayer
81
+ # see issue #3
82
+ if audioStreamPlayer .stream != audioEventStream .audio :
83
+ return
84
+
40
85
var pos = audioStreamPlayer .get_playback_position ()
41
86
var index = - 1
42
87
for t_i in range (len (audioEventStream .eventTimes )):
@@ -49,3 +94,18 @@ func _process(_delta):
49
94
if index != - 1 and lastId != index :
50
95
soundEvent .emit (audioEventStream .name , index , pos )
51
96
lastId = index # Avoid doubles
97
+
98
+ #endregion
99
+
100
+ #region Private API
101
+ func _precondition (err : String ) -> bool :
102
+ if audioStreamPlayer == null :
103
+ push_error (err + ": " , "AudioStreamPlayer is not assigned" )
104
+ return false
105
+ if audioEventStream == null :
106
+ push_error (err + ": " , "No AudioEventStream resource attached!" )
107
+ return false
108
+ return true
109
+
110
+ #endregion
111
+
0 commit comments