How to set stream on AudioStreamPlayer2D

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

Noob question Godot 3!! How to set the stream from the AudioStreamPlayer2D? I’ve tried set it directly, but debugger say, !p_stream.is_valid() is true, that means I set the wrong value.

Here is what I’ve done

export(AudioStream) var audio_sfx

func somefunction():
    sfx.stream = audio_sfx
    sfx.play()

This code will produce !p_stream.is_valid() is true. Any idea?

:bust_in_silhouette: Reply From: dodgyville

This worked for me with AudioStreamPlayer, it might work with AudioStreamPlayer2D?

var speech_player = AudioStreamPlayer.new()
var audio_file = "res://Audio/(filename).ogg"
if File.new().file_exists(audio_file):
    var sfx = load(audio_file) 
    sfx.set_loop(false)
    speech_player.stream = sfx
    speech_player.play()

Yes I know if load / preload will works flowless. But, I want to make it “inspector-able”, so each node can have different sound.

damarindra | 2017-12-02 06:57

:bust_in_silhouette: Reply From: peret

So, I’m pretty sure the reason this happens is that when Godot instantiates your scene it also needs to instantiate your AudioStreamPlayer sfx, which throws this error, because at this point the stream property of sfx is still null. To offer a solution I think we would need more code/context of what exactly you’re trying to do.

My guess is, that you should rethink your approach though. E.g. what about just adding an AudioStreamPlayer node to your scene? And then, when you instantiate that scene, you can change the Player’s stream property in the editor.

Sadly, that was not the case. That was my first scene, no instantiate. I don’t know if this has been fixed or not. AFAIK, I want to achieve reusable AudioStreamPlayer, instead of using a lot of AudioStreamPlayer, I can use only one AudioStreamPlayer and change the stream (clip).

The sfx is not null, I’ve tried to check it with print(sfx)

this might be easy fix with this issues, just load at _ready(), something like
audio_sfx = load(audio_sfx.resource_path)
Well, I haven’t tried it anyway, haven’t in touch with that again.

damarindra | 2018-03-06 02:06