Sound and Music

A video game is going to need sound and music at some point! Otter has both Sound and Music classes to help out with that.  In this very quick example play three sounds and a song with some keyboard presses.

To run the example you're going to need to download the following assets:

sound1.wav (Created with bfxr)

sound2.wav (Created with bfxr)

sound3.wav (Created with bfxr)

music.ogg (Space Sushi soundtrack by Josh Whelchel)

Now onto the code!

using Otter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SoundStuff {
  class Program {
    static void Main(string[] args) {
      // Create a Game.
      var game = new Game("Sound and Music");
      // Start the game with a new SoundScene.
      game.Start(new SoundScene());
    }
  }

  class SoundScene : Scene {
    // Load the sounds into individual Sound objects.
    public Sound SoundOne = new Sound("sound1.wav");
    public Sound SoundTwo = new Sound("sound2.wav");
    public Sound SoundThree = new Sound("sound3.wav");

    // Load the music into a Music object.
    public Music Music = new Music("music.ogg");

    public override void Update() {
      base.Update();

      // Play sounds for the 1, 2, and 3 keys being pressed.
      if (Input.KeyPressed(Key.Num1)) {
        SoundOne.Play();
      }
      if (Input.KeyPressed(Key.Num2)) {
        SoundTwo.Play();
      }
      if (Input.KeyPressed(Key.Num3)) {
        SoundThree.Play();
      }

      // Pause or play the music on the spacebar being pressed.
      if (Input.KeyPressed(Key.Space)) {
        if (Music.IsPlaying) {
          Music.Pause();
        }
        else {
          Music.Play();
        }
      }

      // Adjust the volume of the sounds with up and down keys.
      if (Input.KeyDown(Key.Up)) {
        Sound.GlobalVolume += 0.02f;
      }
      if (Input.KeyDown(Key.Down)) {
        Sound.GlobalVolume -= 0.02f;
      }

      // Adjust the volume of the music with left and right keys.
      if (Input.KeyDown(Key.Right)) {
        Music.GlobalVolume += 0.02f;
      }
      if (Input.KeyDown(Key.Left)) {
        Music.GlobalVolume -= 0.02f;
      }
    }
  }
}

This example cuts straight to the chase and has no graphics or anything so you should only see a black screen when running it.  Pressing 1, 2, and 3 will play sounds, pressing the spacebar will toggle the music, and the arrow keys will adjust the volume of the sound and music.

Note that Otter uses SFML, so its audio capabilities are exactly what SFML provides. This means that the supported file formats for both Sound and Music are the same as SFML's.  The supported file formats are:

ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam, w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64

Examples