Skip to content

[Unity] How to Play Music and Audio

Last Updated on 2021-11-03 by Clay

If you want to play the audio file in Unity, we can divide this task into two types: playing background music and game sound effects.

The background music needs to be played when the game is started or the object is created, and may need to be played repeatedly; the game sound effect should trigger a specific event, such as playing when a food is eaten.

The following is a simple record of how to achieve these two important audio playing function.


Play the background music

Before we start, we must talk about the Audio Listener component. Audio Listener is attached to Main Camera by default. According to the official document, Audio Listener is a microphone-like device. It receives input from any specified Audio Source and plays the sound through the computer.

Therefore, if we want to have the background music (BGM) of the scene, we only need to add the Audio Source component to the Main Camera and put the music we want to play.

Oh, by the way, don't forget to check the Play On Awake and Loop options, so that the music will play when it enters the scene and will continue to play repeatedly after the music is finished.


Play game sound effects

Let's first assume a situation: we manipulate the player and get an accelerated prop. At this time, we should play a sound effect of getting the prop.

We can attach the following script to the play game object.

public class Player : MonoBehaviour {
    // Sounds
    public AudioClip eatSound;
    private AudioSource myAudioSource;

    void Start()
    {
        // Sounds
        myAudioSource = GetComponent<AudioSource>();
    }

    // Trigger
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Items")
        {
            myAudioSource.PlayOneShot(eatSound);
        }
    }
}



Don't forget to drag the sound effect you want to play to the eatSound field in the game editor.

In this way, the eatSound sound effect will be automatically played once when it hits an object whose object label is Items.


References


Read More

Tags:

Leave a Reply