LoginSignup
2
1

More than 3 years have passed since last update.

【Godot】サウンドを動的にロードして再生する方法

Last updated at Posted at 2021-02-10

概要

この記事では、サウンドファイル(*.wav / *.ogg) をGDScript上で実行時にロードして再生する方法を説明します

通常のサウンド再生

通常、サウンドを再生する場合には、AudioStreamPlayer2D にサウンドファイルを割り当てて再生する、という方法を行います。
Godot_Engine_-_TestSound_-_Main_tscn____.png

ただ、この方法だと異なるサウンドファイルを追加するたびに、登録が必要となり不便です。

GDScriptでのサウンドの読み込みと再生

例えば、以下のサウンドファイルがプロジェクトに追加されているとします。

  • 1.wav
  • 2.wav
  • 3.wav

Godot_Engine_-_TestSound_-_Main_tscn____.png

まずは以下のように AudioStreamPlayer2D を追加して、スクリプトを追加します。

Main.gd
extends Node2D

func _ready():
    pass # Replace with function body.

func _play_sound(idx):
    # 指定したIDのサウンドを再生
    # 一旦停止する
    $AudioStreamPlayer2D.stop()

    # サウンドファイルのパスを作成
    var path = "res://%d.wav"%idx

    # 動的に読み込んで steam に割り当てる
    $AudioStreamPlayer2D.stream = load(path)

    # 再生
    $AudioStreamPlayer2D.play()

func _process(delta):
    if Input.is_action_just_pressed("ui_left"):
        _play_sound(1)
    if Input.is_action_just_pressed("ui_up"):
        _play_sound(2)
    if Input.is_action_just_pressed("ui_right"):
        _play_sound(3)

画像の動的読み込みと同様、load() を使うことでサウンドファイルを動的に読み込んで再生します。

もしアクションゲームなどでサウンド再生のレスポンスの速さを出すために、毎回ロード処理を行いたくない場合は、preload() でサウンドファイルを読み込みます。
ただしその場合、動的にパスは作れず、固定のパスとなります。

Main.gd
extends Node2D

var Snd1 = preload("res://1.wav")
var Snd2 = preload("res://2.wav")
var Snd3 = preload("res://3.wav")

func _ready():
    pass # Replace with function body.

func _play_sound(idx):
    $AudioStreamPlayer2D.stop()

    match idx:
        1:
            $AudioStreamPlayer2D.stream = Snd1
        2:
            $AudioStreamPlayer2D.stream = Snd2
        3:
            $AudioStreamPlayer2D.stream = Snd3

    $AudioStreamPlayer2D.play()

func _process(delta):
    if Input.is_action_just_pressed("ui_left"):
        _play_sound(1)
    if Input.is_action_just_pressed("ui_up"):
        _play_sound(2)
    if Input.is_action_just_pressed("ui_right"):
        _play_sound(3)

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1