Skip to content

Godot:AudioStreamPlayer

godot에서 음향효과 재생 방법.

Example

using Godot;
using System;

public class PianoOctave : MarginContainer
{
    private AudioStreamPlayer _do;

    public override void _Ready()
    {
        _do = CreateAudioStreamPlayer("C");
    }

    private AudioStreamPlayer CreateAudioStreamPlayer(string name)
    {
        var player = new AudioStreamPlayer();
        var stream = ResourceLoader.Load<AudioStreamOGGVorbis>("res://Assets/Piano/do.ogg");
        stream.Loop = false; // 반복 금지.
        player.Stream = stream;
        AddChild(player); // 자식으로 추가해야 정상적으로 재생된다!
        return player;
    }

    public void _on_Do_pressed()
    {
        _do.Play(); // 재생!
    }

    // ...
}

다른 경로의 음악파일 재생

res://로 시작하지 않는 다른 경로의 파일을 읽는 방법:

using Godot;
using System;

public class YourScript : Node
{
    private AudioStreamPlayer audioPlayer;

    public override void _Ready()
    {
        audioPlayer = GetNode<AudioStreamPlayer>("YourAudioStreamPlayerNode");

        string filePath = "/path/to/your/file.ogg"; // 다운로드 경로 이외의 Ogg 파일의 경로를 지정합니다.
        File file = new File();

        if (file.Open(filePath, File.ModeFlags.Read) == Error.Ok)
        {
            byte[] data = new byte[(int)file.GetLen()];
            file.GetBuffer(data);
            file.Close();

            var stream = new AudioStreamOGGVorbis();
            stream.Data = data;

            audioPlayer.Stream = stream;
            audioPlayer.Play();
        }
        else
        {
            GD.Print("Failed to load audio file.");
        }
    }
}

See also

Favorite site