Tutorials

Playing audio samples

Sample name: SampleAudio
Script source code file: sample/audio/main.lua

SampleAudio

The goal of this tutorial is to show you
  • how to use audio samples
  • the difference between 2d and 3d sounds
New functions in this tutorial

createSample()
loadSample()
playSample()

Run sampleAudio.exe. Every two seconds you should hear a "pling" and if you press space you should hear a water splash.

Open main.lua which is in /sample/audio to see the code of this example.

First there are three variables: time, sample1Id and sample2Id

init()


The first line creates a sample using the createSample function and stores the id in the variable sample1Id. The only argument here is the name of the sample.

 sample1Id = createSample("sample1");

The sample is like an empty shell which needs filling with an audio file. That’s what the second line does. It needs the id of the sample and the filename as arguments. The last argument is a boolean and defines whether your sound is 3D or not.

3D sounds can be placed in your scene. They are surrounded by a sphere which defines the distance over which the sound can be heard. The closer you get to the sound the louder it is.

A 2D sound simply plays at full volume when it is triggered.

For the filename you need to indicate the relative path.

 loadSample(sample1Id, "sample/audio/sample1.wav", false);

keyEvent()


If you press the space key, the sample2 is played via the playSample function. Here is how this function is described in the documentation:

playSample

Description
Play sample object
Definition
function playSample(integer objectId, integer loops, float volume, float offset)
Arguments
integerobjectIdid of sample object
integerloopsnumber of loops [0,n] 0 = endless looping
floatvolumevolume [0,1]
floatoffsetoffset in milliseconds

The offset defines from which position within the sample it starts playing. E.g. if you define an offset of 3000, the first three seconds of your sample are cut off the first time the sample gets played.

if sym == Input.KEY_space then
  playSample(sample2Id, 1, 1, 0);
end;

update()


First the time is increased and if it is larger than 2000 milliseconds the sample1 is played and the time is reset to 0.

function update(dt)

  time = time + dt;

  if time > 2000 then
    playSample(sample1Id, 1, 1, 0);
    time = 0;
  end;
end;