crabs-game/scripts/MusicPlayer.gd

69 lines
1.6 KiB
GDScript3
Raw Permalink Normal View History

extends Node
var fading = false
var animation_time : float
var animation_duration : float
var target_track : AudioStreamPlayer
var previous_tracks : Array
2020-08-18 12:02:14 +02:00
func play(music, offset=0, duration=1):
print('Play music: ' + music)
var path = "res://sounds/" + music + ".ogg"
2020-08-20 18:52:24 +02:00
# if !File.new().file_exists(path):
# path = "res://sounds/" + music
# assert(File.new().file_exists(path))
var stream = load(path)
target_track = get_free_track()
previous_tracks = get_playing_tracks()
if previous_tracks.size() > 0:
fading = true
animation_time = 0
animation_duration = duration
target_track.stream = stream
target_track.play(offset)
2020-08-18 12:02:14 +02:00
func fade_out(duration=1):
target_track = null
previous_tracks = get_playing_tracks()
fading = true
animation_time = 0
animation_duration = duration
func get_playing_tracks() -> Array:
var tracks = []
for track in get_children():
if track.playing:
tracks.append(track)
return tracks
func get_free_track() -> AudioStreamPlayer:
var free_track = null
for track in get_children():
if !track.playing:
free_track = track
if free_track == null:
free_track = AudioStreamPlayer.new()
2020-08-20 19:18:43 +02:00
free_track.volume_db = -8
add_child(free_track)
print(free_track)
return free_track
func _process(delta):
if fading:
animation_time += delta
var p = clamp(animation_time / animation_duration, 0, 1)
if target_track != null:
2020-08-18 12:02:14 +02:00
target_track.volume_db = lerp(-90, 0, p)
for previous_track in previous_tracks:
2020-08-18 12:02:14 +02:00
previous_track.volume_db = lerp(0, -90, p)
if p == 1:
fading = false
for previous_track in previous_tracks:
previous_track.stop()
previous_track.queue_free()