Godot:AudioStreamPlayer
lastmod 2023-05-25created 2020-11-147 edits
How to play sound effects in 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(); // 재생!
}
// ...
}
Playing music files from other paths
How to read files from other paths that do not start with 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
- godot
- Godot:RecordingWithMicrophone - how to record from a microphone in Godot
Favorite site
- Godot 3 Tutorial– Sound FX and Music – GameFromScratch.com
- Sync the gameplay with audio and music — Godot Engine (stable) documentation (Korean) - syncing gameplay with audio and music