0
0
Unityframework~5 mins

Audio Source component in Unity

Choose your learning style9 modes available
Introduction

The Audio Source component plays sounds in your game. It lets you add music, sound effects, or voices to objects.

You want a character to speak or make noise.
You need background music that plays during a scene.
You want sound effects when a player interacts with objects.
You want to play a sound when something happens, like a door opening.
You want to control volume or pitch of sounds on specific objects.
Syntax
Unity
AudioSource audioSource = gameObject.AddComponent<AudioSource>();
audioSource.clip = yourAudioClip;
audioSource.Play();
You must assign an AudioClip to the AudioSource before playing sound.
AudioSource can be added to any GameObject in your scene.
Examples
Play a jump sound when the player jumps.
Unity
AudioSource audioSource = gameObject.AddComponent<AudioSource>();
audioSource.clip = jumpSound;
audioSource.Play();
Play sound at half volume using an existing AudioSource on the object.
Unity
AudioSource audioSource = GetComponent<AudioSource>();
audioSource.volume = 0.5f;
audioSource.Play();
Make the sound repeat continuously, like background music.
Unity
audioSource.loop = true;
audioSource.Play();
Sample Program

This script adds an AudioSource to the object it is attached to. When the game starts, it plays the assigned sound clip once.

Unity
using UnityEngine;

public class PlaySoundOnStart : MonoBehaviour
{
    public AudioClip soundClip;
    private AudioSource audioSource;

    void Start()
    {
        audioSource = gameObject.AddComponent<AudioSource>();
        audioSource.clip = soundClip;
        audioSource.Play();
    }
}
OutputSuccess
Important Notes

Make sure your AudioClip is assigned in the Inspector or via code before playing.

Use the loop property to repeat sounds like music.

You can control volume, pitch, and spatial blend for 3D sound effects.

Summary

The Audio Source component plays sounds attached to game objects.

Assign an AudioClip and call Play() to hear the sound.

You can control volume, looping, and other sound settings on the AudioSource.