how to pause and resume a sound ?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By nonomiyo

Hello, I want to pause my sound when on pause menu. I couldn’t get “get_tree().paused = true” to pause my sounds, so this is what I tried :

in the pause function :

var pauseposition = get_node("myStreamPlayer2D").get_playback_position();
get_node("myStreamPlayer2D").playing = false;

in the resume function :

get_node("myStreamPlayer2D").seek(pauseposition);
get_node("myStreamPlayer2D").playing = true;

This resume function always restarts my sound at the beginning.
How should the seek() function be used ?

thanks !

:bust_in_silhouette: Reply From: ZacB
get_node("myStreamPlayer2D").play()
get_node("myStreamPlayer2D").stop()

Also : You can use $myStreamPlayer2D rather than get_node("myStreamPlayer2D")

no, it’s not working.

It stops and restarts the sound instead of resuming it where it has paused…

nonomiyo | 2018-07-28 07:52

do $myStreamPlayer2D.play()
then create a var temp = $myStreamPlayer2D.get_playback_position( )
then $myStreamPlayer2D.stop()
then $myStreamPlayer2D.play()
then $myStreamPlayer2D.advance(temp)

ZacB | 2018-07-28 17:43

thanks it’s working now ! Except the “advance” command doesn’t exist, I used “seek”:

$myStreamPlayer2D.play()

var temp = $myStreamPlayer2D.get_playback_position( )
$myStreamPlayer2D.stop()

$myStreamPlayer2D.play()
$myStreamPlayer2D.seek(temp)

nonomiyo | 2018-07-28 21:31

In my case (Godot version v3.2.2.stable.official) it doesn’t work with seek(). Actually seek() is no required. The following is enough:

# 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)

music_position - is a global variable, declared as:

# audio position for pause and resume
var music_position = 0

Elendir | 2020-09-11 09:40