Playing a sound from script

In our last post, the sound we have been playing automatically starts when the scene is loaded. This behaviour can be useful in the case of an ambience or background music. However, most sounds in a game are event-based and are triggered by actions coming from the AI or the player: firing a weapon, jumping, hitting the ball, picking up an object and so on…

In this post, we will see how to start sound playback from a script, exactly when we want.  As a simple example, let’s start a sound when we click on a ball with the mouse.

First make sure the CRIWARE plug-in package has been imported in your project and that its components have been initialized correctly. Also confirm that binary Cue Sheets (ACB files) have been loaded. Refer to this post if you have any doubt.

Now let’s create our ball. To do so, select the “GameObject -> 3D Object -> Sphere” menu command. Select the sphere in the Inspector, press “Add Component” and add a CRI Atom Source from the CRIWARE submenu and type in the names of the CueSheet and the Cue. This time, we want to keep the “Play On Startof the CRI Atom Source cleared, so that the sound does not start automatically.

It’s time to create our script!  Select the sphere in the Hierarchy view and right-click in the Project view to create a C# script.  Rename it to PlayBallSFX.cs. Drag and drop PlayBallSFX.cs onto the sphere in the Hierarchy view to add it to the ball.

Start MonoDevelop and edit the PlayBallSFX.cs script as shown below.


public class PlayBallSFX : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    void OnMouseDown() {
        CriAtomSource audio = (CriAtomSource)GetComponent("CriAtomSource");
        audio.Play();   
    }
}

In this script, the OnMouseDown handler is used to define what happens when the mouse button is clicked. That is where the magic happens in our case! First, we get the CRI Atom Source component assigned to the object.  Then, the Cue specified for this CRI Atom Source is played.  To do that, all we have to do is call the Play() function of the CRI Atom Source component.

Once you have access to this component, there are a lot of very interesting things you can do, like changing its pitch and volume in real-time, or even its audio positioning! We will all see that in the coming posts but for now, click on the Play button in Unity to execute the game.  You can see the ball but no sound can be heard. However, click on it and the sound starts playing!