Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Medium

Audio in Unity

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

In this article, we will learn how we can add audio in unity. Adding audio remains one of the most crucial parts of game development as most consumers fall in love with the game when they like the sound effects of the particular game. In in-game creation and while examining its nature in general, audio is an intriguing idea to explore. Its perception is influenced by various things that must be considered while attempting to regulate or utilise it. The position of the source and how rapidly it moves, if it moves at all, are essential factors in auditory perception.

Adding audio in unity

Did Doppler’s effect haunt you in Physics back in your school days? Did you think that doppler’s effect will never cross paths with you in your college days? Then we have some bad news for you!!🤣🤣 It is back and will be used in adding audio in Unity 3D. In Unity, the position of an audio source is critical for identifying its source. For instance, we must ensure that a gameObject playing the sound of a waterfall corresponds to a genuine waterfall gameObject and that the player's experience of that sound is accurate. Increasing the volume as the player approaches, ensuring that the audio panning changes when the waterfall's relative position to the player shifts, and so on.

Following is a screenshot of adding audio in unity.

Screenshot of adding audio in unity

In the next section, we’ll see the key Elements of Audio in Unity.

The two main Elements related to Audio in Unity are as follows:

  • Audio Listener
  • Audio Source
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Audio Listener

This component is automatically associated with the primary camera when you build a scene. It has no qualities because its sole purpose is to serve as a perception point. It is recommended that the Audio Listener should be left alone.

Audio Source

This is the component that controls how the sound plays. When working with vast, complex systems, it's best to create an empty gameObject to act as the Audio Source and make it a child, so you know exactly where the Audio Source is. 

We may experiment with several properties of the Audio Source component. Pitch, panning, and spatial blending are all included, and there are options for adding Doppler Effects and loudness rolloffs if you access the 3D Sound Settings.

The AudioClip slot, on the other hand, is what we're most interested in. That's where you'll play the sound effect. Unity supports a variety of popular sound formats, such as .mp3 and.ogg.

In the next section, we'll see how to Construct Audio Sources.

Construct and adding Audio Sources

Audio Sources have no effect unless an Audio Clip is assigned to them. The actual sound file that will be played back is the Clip. Source acts as a regulator, allowing you to start and stop playing that clip and change other audio parameters.

The steps for constructing a new audio source are as follows:

  • Your audio files should be imported into your Unity project. Now, these are Audio Clips.
  • From the menubar, select GameObject > Create Empty.
  • Select Component > Audio > Audio Source with the new GameObject selected.
  • Locate the Audio Clip property on the Audio Source Component in the Inspector and assign a clip, either by dragging one from the Project Window or by selecting a clip from the list by clicking the little circle icon to the right of the Inspector property.


Take into consideration that If you only want to generate an Audio Source for one Audio Clip in your Assets folder, move it to the scene view. A GameObject with an Audio Source component will be produced for it immediately. Moving a clip onto an existing GameObject creates a new Audio Source if one isn't already there. The newly moved clip will replace the source's current Audio Source if the item already has one.

It will be difficult to understand this without any example, so let us see an example of a game with fireballs. We will add the audio clip whenever the fireball will be shooted by the user and once again when the fireballs will collide.

Let us see the code for it

Code Implementation

In the following code, we will be creating a class named ‘shoot’ with mono behaviour. Inside this, we have created two methods and whenever the input ‘spacebar’ will be pressed the audi clip added will be played.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//Creating a Shoot class

public class Shoot: MonoBehaviour
{
    public GameObject FireBall;
    private AudioSource src;
    
    void Initiate()
    {
        src = GetComponent<Audiosrc>();
    }
    
    void Update() 
    {
       
         // When we hit the spacebar
        
        if(Input.GetKeyDown(KeyCode.Space))
        {
          
              // Instantiating the FireBall object
            
            Instantiate(FireBall,
                new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, 0),
                new Quaternion(0, 0, 0, 0));
                
              // Calling the play function to play the sound
            
            src.Play();
        }
    }
}


The above code will help in adding sound whenever the user shoots.

Enjoy your game with sound effects!

Let us now see the code to add the sound when the balls collide.

Code Implementation

In this code we have created a class collision, and a method which will add audio whenever target will hit!

public class Collison : MonoBehaviour
{
    private AudioSource src;
    
    void Start()
    {
        src = GetComponent<Audiosource>();
    }
    
    void onCollisionEnter2D(Collision2D col) 
    {
        // When we hit the target
                
                if(col.gameObject.tag == "Bullet")
        {
            Debug.Log("Target Collided");
            
            // calling the AddScore method
           
             ScoreBehaviour.AddScore();
            
            // play the sound
            src.Play();
            
            Destroy(col.gameObject);
            Destroy(gameObject);
        }
    }
}


After successfully executing the programs the audio will be played while playing the game

Sample Audio

That’s the end of this blog! Hope you will be now able to add nice audio clips to your next game!

Let us now see some of the FAQs related to the topic.

Frequently Asked Questions

What is an audio source?

A component that permits sound to be played in your scene is called an AudioSource. It also contains audio control features such as the Play, Pause, volume, loop and all other attributes and methods required to control how your sounds are played back.

What role does audio play in Unity?

Unity provides a temporary Audio Source to play the clip from when you use Play Clip At Point. Unity creates a new, temporary Audio Source to play the clip from behind the scenes and then properly dispose of it once the clip is finished. When this happens, a new Game Object will exist and disappear in the editor.

Is it possible to use MP3 in Unity?

Yes, it is possible to use MP3 in Unity. Although the audio data will be small, it will need to be decompressed at runtime, which will add processing time. Unity will encode the audio to either Ogg Vorbis (Mac/PC/Consoles) or MP3, depending on the target (Mobile platforms).

Are m4a files compatible with Unity?

Unity has its audio importers, and while m4a worked in Unity 2.5, it does not work with Unity 2.6 (Mac or PC).

What is an audio listener in Unity?

The Audio Listener works similar to a microphone. It takes audio input from any given Audio Source in the scene and outputs it through the computer speakers. The Audio listener should be attached to the Main Camera in most cases.

Conclusion

In this article, we have extensively discussed Adding Audio in Unity. We have learned a bit about Audio Listener and Audio Source, the construction of Audio Source, and also some FAQs related to this topic.

After reading about Unity 3D Canvas, are you not feeling excited to read/explore more articles on related topics? Don’t worry. Coding ninjas has you covered. To learn, see Introduction to Game Development, Game development life cycle modelGame Development, and UI Element testing, or you can start your career in game development by reading out  Game development as a career.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc., you must look at the problems, interview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Thankyou
Topics covered
1.
Introduction
2.
Adding audio in unity
3.
Audio Listener
4.
Audio Source
5.
Construct and adding Audio Sources
5.1.
Code Implementation
5.2.
Code Implementation
6.
Frequently Asked Questions
6.1.
What is an audio source?
6.2.
What role does audio play in Unity?
6.3.
Is it possible to use MP3 in Unity?
6.4.
Are m4a files compatible with Unity?
6.5.
What is an audio listener in Unity?
7.
Conclusion