Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

Godot 3 Tutorial– Sound FX and Music


This video covers all aspects of audio using the Godot 3 game engine.  We cover how to play audio using an AudioStreamPlayer, then look at how to create one dynamically.  We then look in depth at how audio buses work, how to create special affects.  We also look at how to perform positional audio and how to limit it’s playback using Area2D.  After this tutorial you should know everything you need to be effective with audio in Godot.


The Video

Assets and Code Samples

DynamicAudio.gd

extends Node

func _ready():
  var player = AudioStreamPlayer.new()
  self.add_child(player)
  player.stream = load("res://belch.wav")
  player.play()

SpritePositionalAudio.gd

extends Sprite

func _ready():
  get_viewport().audio_listener_enable_2d = true
  $AudioStreamPlayer2D.play()

func _process(delta):
  if self.position.x > 0 - self.texture.get_width():
    move_local_x(-1)
  else:
    self.position.x = get_viewport().get_visible_rect().size.x

OptionButton.gd

extends OptionButton

var files = []
func _ready():
  var player = get_tree().get_root().get_node("Node/AudioStreamPlayer")
  
  var dir = Directory.new()
  if dir.open("res://") == OK:
    dir.list_dir_begin()
    var file = dir.get_next()
    while (file != ""):
      if file.ends_with("wav") or file.ends_with("ogg"):
        files.append(file)
      file = dir.get_next()
      
    for i in range(files.size()):
      self.add_item(files[i],i)
      
    player.stream = load("res://" + files[0])

func _on_OptionButton_item_selected(ID):
  if files.size() > 0:
    var player = get_tree().get_root().get_node("Node/AudioStreamPlayer")
    player.stream = load("res://" + files[ID])

PlayButton.gd

extends Button

var player

func _ready():
  player = get_tree().get_root().get_node("Node/AudioStreamPlayer")
  

func _on_PlayButton_pressed():
  if get_node("/root/Node/PanelContainer/VBoxContainer/LoopContainer/CheckBoxLoop").pressed == true:
    setLoopMode(player.stream, 1)
  else:
    setLoopMode(player.stream, 0)
  
  print("Playing sound")
  player.play()   
    
func setLoopMode(stream,loop):
  if(stream is AudioStreamOGGVorbis):
    stream.loop = bool(loop)
  else: #Its a wave
    stream.loop_mode = loop


func _on_StopButton_pressed():
  player.stop()

Back to Tutorial Series Homepage





blog comments powered by Disqus


See More Tutorials on DevGa.me!

Month List