Sound in a game can really make a big difference. In ShiVa, we have the option to add background music in the Ambience Editor window, but we can also add sound effects for individual objects. We are going to use the SoundBank Editor window to add a low-level constant engine noise for our ship.
Arrange your editor so that you can see the Data Explorer, Scene Explorer, and SoundBank Editor windows. I also like to have the Scene Viewer window open so I can quickly reopen the scene if needed. This arrangement is shown in the following screenshot:
The SoundBank Editor window is used to manage sound effects for an object and can only create, play, or rearrange the index of sounds.
The sound that I am going to use is from soundbible.com
and it is called Rocket Thrusters. There are plenty of sites that have free sounds, but you'll want to make sure you check the licensing before using anything you download. I modified the sound a bit in Audacity so that it would loop cleanly.
To add sound in our game, do the following steps:
ShipSounds
.You should now have a sound listed, as shown in the following screenshot:
The index is to the left of the title and the length of the clip is to the right. Now we have to add the SoundBank to our ship and set it to play when the game starts.
Find the ship in the Scene Explorer window, right-click on it and select Controllers | Sound | Set a SoundBank and select ShipSounds. To set it playing, we will change our MainAI option's onInit
code to read like the one given in the following code snippet:
-- Set the current scene to Level1 and -- compare to nil to make sure the scene loaded if( application.setCurrentUserScene ( "Level1" ) ~= nil ) then -- Get a handle to the ship by using the ships 'name' this.hShip ( application.getCurrentUserSceneTaggedObject ( "Ship" ) ) -- Play the rocket sound sound.play ( this.hShip ( ), 0, 0.5, true, 0.5 ) else -- Send an error message to the log -- if the scene can not be set log.error ( "Unable to load initial scene" ) end
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
The play
function of the sound
object is sound
.play
( hObject
, nSoundIndex
, nVolume
, bLoop
, nPriority
), where:
hObject
is the object that will play the sound—in this case the shipnSoundIndex
is the index of the sound, and if you remember, ours was 0
nVolume
is between 0
and 1
bLoop
is true
if you want the sound to loopnPriority
is between 0
and 1
—some devices have caps on the number of sounds playing simultaneously, so this determines which sounds take precedenceThat's it! Hit the Play button and watch our newly decorated ship spin in circles while its engines roar away!
18.188.131.255