Creating the visual elements of a game is only half of the game, adding sounds to your game are just as important as developing amazing shaders. Unity's sound system is flexible and powerful.
Unity can import most standard audio file formats and has features for playing sounds in 3D space, optionally with effects like echo and filtering applied. Even Unity can also record audio from any available microphone on a user's machine for use during gameplay or storage and transmission.
There are two components related to Audio in Unity; they are:
Let's see these components one by one:
Audio Listener is the component that is automatically attached to the main camera every time you create a scene. It does not have any properties since its only job is to act as the point of perception.
This component listens to all audio playing in the scene and transfers it to the system's speaker. It acts as the ears of the game. Only one AudioListener should be in a scene for it to function properly.
The audio source is the primary component that you will attach to a GameObject to make it play sound. This is the component that is responsible for playing the sound.
To add the Audio Source component, select one GameObject, and go to the Inspector tab. Click on Add Component and search for Audio Source.
Select Audio Source.
Audio source will playback an Audio Clip when triggered through the mixer, through code or by default, when it awakes.
An Audio Clip is a sound file that is loaded into an AudioSource. It can be any standard audio file such as .wav, .mp3, and so on. An Audio Clip is a component within itself.
Playing a Sound
Let's add a button that plays a sound when it is clicked. For this, first of all, create a sprite and do one color. Here, I am creating a circle sprite and making it red.
Now, attach an Audio Source component to this circle sprite.
Now, you have to import one audio file. Here, I am downloading success sound. To download it, click here.
Drag this sound file into Assets.
Drag this sound clip from Assets to the Audio clip slot in our sprite's Audio source component.
For this add 'Circle Collider 2D' component.
Attach this script to your circle script. Now play the game. Clicking on the button (red circle sprite) should show a message to the console, and you should hear the success sound.