how to play AudioStreamPlayer2D from AudioStreamSample

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By noonewon4
using Godot;
using System;

public class exam : AudioStreamPlayer2D
{
    private AudioStreamPlayer2D audioStreamPlayer;
    private AudioStreamSample audioStreamSample;
    public override void _Ready()
    {
        audioStreamPlayer = GetParent().GetNode< AudioStreamPlayer2D>("AudioStreamPlayer2D");
        audioStreamSample = new AudioStreamSample();
        audioStreamSample.SetPath("res://PianoSounds/A5.ogg");
        audioStreamPlayer.SetStream(audioStreamSample);

        audioStreamPlayer.Play();
    }

}

I tried this out but doesn’t work
I know it works when click load button in AudioStreamPlayer2D
but i have to load AudioStreamSample from coding
thanks

:bust_in_silhouette: Reply From: Zylann

Try to replace:

    audioStreamSample = new AudioStreamSample();
    audioStreamSample.SetPath("res://PianoSounds/A5.ogg");

By:

    audioStreamSample = ResourceLoader.Load<AudioStream>("res://PianoSounds/A5.ogg")

OGG files are not imported as AudioStreamSample, they are AudioStreamOGGVorbis. It should be better for you to use the base class AudioStream when declaring the variable.

error : System.InvaildCastException: Specified cast is no vaild.

maybe I should load AudioStream from Editor

noonewon4 | 2019-09-10 13:59