How does Godot play music from a file through a script?

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

Let’s say we have an AudioStream…

It is clear that we can drag the track there with the mouse, but how to select a file for playback through the script? More precisely, I want to connect an array of tracks to the game so that they are randomly selected…
I suspect that you need to somehow get to the Stream/Resourse/Path/“res://…” field and add a new music file there, but how do you do that?
Please write a code example of how it should work.

:bust_in_silhouette: Reply From: PolyBytes

So what you would want to do is setup an Array of AudioStream references and then randomly select one through a script.

Here is the script I made as an example:
Scripting example for selecting a random audio stream from an Array of AudioStream references.

And with the:

@export var random_audio_streams: Array[AudioStream]

in the inspector it will allow you to add streams to the array like this:
Export variable usage example in inspector.

Obviously the code does not have to be put in the _ready() function but that is what I did in this case for testing.