0 votes
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

in Engine by (34 points)
edited by

1 Answer

0 votes

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.

by (27,595 points)

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

maybe I should load AudioStream from Editor

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.