Controllable music player in 4.0.2

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

I’ve just switched to version 4.0.2 of Godot, and I’m trying to program a radio within my game, that allows you to change what song is playing. But it only plays one song.
I’ve tested it, and it seems like it’s trying to change something, but it isn’t succeeding. This is the code I’ve used:

var MusicChoice1 = preload("res://Music and Audio/Lucid Mind OST/Siesta.ogg")
var MusicChoice2 = preload("res://Music and Audio/Lucid Mind OST/Anthropology.ogg")
var ChosenSong = 0

@warning_ignore("unused_parameter")
func _process(delta):
ChosenSong = MusicChoice1
if !$AudioStreamPlayer3D.is_playing():
	$AudioStreamPlayer3D.stream = ChosenSong
if Input.is_action_pressed("Interact"):
	if ChosenSong == MusicChoice1:
		$AudioStreamPlayer3D.stop()
		ChosenSong = MusicChoice2
		$AudioStreamPlayer3D.play()
	if ChosenSong == MusicChoice2:
		$AudioStreamPlayer3D.stop()
		ChosenSong = MusicChoice1
		$AudioStreamPlayer3D.play()

Is there a way to fix this issue?

To be exact, when I interact with the radio in my game, it restarts the song that’s playing.

Entity2020 studios | 2023-04-30 10:24

:bust_in_silhouette: Reply From: jgodfrey

You’re assigning the new music reference to the ChosenSong variable, but you’re never assigning that to the AudioStreamPlayer3D. After changing the song, you need to assign it to the player. For example…

if Input.is_action_pressed("Interact"):
    if ChosenSong == MusicChoice1:
        $AudioStreamPlayer3D.stop()
        ChosenSong = MusicChoice2
        $AudiostreamPlayer3D.stream = ChosenSong
        $AudioStreamPlayer3D.play()

While your code is probably more complex than necessary, that should work.

It now crashes at this part of the code:

		if ChosenSong == MusicChoice1:

And it gives me the error message: “Invalid operands ‘int’ and ‘Object’ in operator ‘==’.”

Entity2020 studios | 2023-05-02 15:21

Hmmm. You’re code must not look exactly like what I expect now…

However, probably changing this:

var ChosenSong = 0

to this:

var ChosenSong

…will fix the error you report.

jgodfrey | 2023-05-02 15:30