How do you randomize music

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Dava
:warning: Old Version Published before Godot 3 was released.

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

:bust_in_silhouette: Reply From: 807

_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.`

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

_ready(), _on_finished, etc.

kidscancode | 2017-09-05 01:12

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.

keke | 2017-09-05 01:26

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

keke | 2017-09-05 01:30

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

807 | 2017-09-05 07:34

The solution :smiley:

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!

Dava | 2017-09-05 19:53