(CSGC) Audio Lesson

Audio

Sounds are used in games to enhance gameplay. Sounds are used to signal different events such as introduction, winning, losing, or an achievement.  

Greenfoot has a class called Greenfoot Sound for playing audio in Greenfoot. To be playable, the sound file must be located in the sounds folder inside the scenario folder. A Greenfoot Sound loads the audio from the sound file.

Most files of the following formats are supported: AIFF, AU, WAV, MP3 and MIDI.

Obtaining Sound Files

You can copy sounds from other Greenfoot projects or download sounds from various free sound libraries on the internet. You can also record your own sounds using a sound recording program. Many programs are available free on the internet.  

Most files of the following formats are supported: AIFF, AU, WAV, MP3 and MIDI.

Methods in Greenfoot Sound

Method Summary
All Methods, Instance Methods
Concrete Methods, Modifier and Type, Method and Description

int
getVolume ()
Get the current volume of the sound, between o (off) and 100 (loudest.)

boolean
isplaying ()
True if the sound is currently playing.

void
pause()
Pauses the current sound if it is currently playing.

void
play ()
Start playing this sound.

void
playLoop()
Play this sound repeatedly in a loop.

void
setVolume (int level)
Set the current volume of the sound between o (off) and 100 (loudest.)

void
stop ()
Stop playing this sound if it is currently playing.

Using the Sound Methods

You must create a sound from the constructor before you can use a sound.

Constructor and Description
GreenfootSound (java.lang.String filename) Creates a new sound from the given file.

public GreenfootSound introSound = new GreenfootSound("intro.mp3");

In the FlyingBird program, an intro sound is played in a loop if the title screen is showing and the objects have not been added.

if (showTitleScreen && !titleObjectsAdded)
{
addObject (new Transitions ("black"), getWidth()/2, getHeight() / 2); addObject (logo, getWidth()/2, getHeight() / 250); addObject (startButton, getWidth()/2, getHeight()/2+25); introSound.playLoop();
titleObjectsAdded = true;
}

One the game starts, the intro sound is stopped using the stop() method.  

if (showTitleScreen && !titleObjectsAdded)
{
addObject (new Transitions ("black"), getWidth()/2, getHeight() / 2); addObject (logo, getWidth()/2, getHeight() / 250); addObject (startButton, getWidth()/2, getHeight()/2+25); introSound.playLoop();
titleObjectsAdded = true;
}

[CC BY 4.0] UNLESS OTHERWISE NOTED | IMAGES: LICENSED AND USED ACCORDING TO TERMS OF SUBSCRIPTION