Page 1 of 1

How to Resume and Pause Music

Posted: Fri Aug 11, 2023 4:13 am
by dumbOldMan
This will teach you on how to pause and resume an audio stream,

Here's the code:
This code is credits to Elinder from the GodotEngine Forum
The link is here: https://ask.godotengine.org/31254/how-t ... me-a-sound

The code:

Code: Select all

#music_position - is a global variable, declared as:
 # audio position for pause and resume
var music_position = 0

# Pressing F3 will toggle music
if Input.is_action_just_pressed("ui_f3"):
   music_position = $AudioStreamPlayer2D.get_playback_position()
    $AudioStreamPlayer2D.stop()
else:
    $AudioStreamPlayer2D.play(music_position)
If your using a global autoload AudioStream and a checkbox as the button:

Code: Select all

#music_position - is a global variable, declared as:
 # audio position for pause and resume
var music_position = 0

func _on_CheckBox_toggled(button_pressed: bool) -> void:
	if button_pressed:
		$'/root/AudioStreamPlayer'.play(music_position)
	else:
		music_position = $'/root/AudioStreamPlayer'.get_playback_position()
		$'/root/AudioStreamPlayer'.stop() 
The code above assumes that the AudioStreamPlayer is not Autoplay, if it is, just swap the code.. It will still works..