0 votes

I am trying to get random music to play on my app, when the user runs the program, a random music will play and when it finishes, it will choose another random music, with this code:

extends StreamPlayer

const tracks = [
  'music_one',
  'music_two',
  'music_three',
  'music_four'
]

 func _ready():
     var rand_nb = Randi() % tracks.size()
     var audiostream = load('res://music/' + tracks[rand_nb] + '.ogg')
     set_stream(audiostream)
     play()
     pass

Only the first music in the list music_one plays and when it finishes, no other music plays, I also want music to keep playing even when the user changes scene but I don't know how to do that

in Engine by (119 points)

1 Answer

+2 votes

_ready() only executes itself 1 time. You should use a signal (in StreamPlayer the signal is finished ()) and connect this signal to the main node. In the _on_finished function (i don“t know if this is the name, look at the signals of StreamPlayer in inspector) you can "replay" or whatever you want.`

by (341 points)
edited by

Place backticks: ` around code snippets to keep from interpreting _ as formatting code:

_ready(), _on_finished, etc.

Your code might look like

extends StreamPlayer

const tracks = [
  'music_one',
  'music_two',
  'music_three',
  'music_four'
]

 func _ready():
      connect("finished" ,self, "play_random_song")
      play_random_song()

func play_random_song():
     var rand_nb = Randi() % tracks.size()
     var audiostream = load('res://music/' + tracks[rand_nb] + '.ogg')
     set_stream(audiostream)
     play()

(untested)

Try reading this.

Also, keeping music playing over scene changes should be possible.
Check this out.

Formated done, but text becomes bloody :) :) :)

The solution :D

extends StreamPlayer

 const tracks = [
    'music_one',
    'music_two',
    'music_three',
    'music_four'
   ]

   func _ready():
      randomize()

      connect("finished" ,self, "play_random_song")
      play_random_song()

   func play_random_song():
      randomize()

      var rand_nb = Randi() % tracks.size()
      var audiostream = load('res://music/' + tracks[rand_nb] + '.ogg')
     set_stream(audiostream)
     play()
     pass

Then you make the music scene autoload in the project manager instead of instanciating it in other scenes Thanks!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.