How to randomize sound

Sound Variation Scripts

Below is a component for unity which will allow you to play a random sound and allow you to modify the pitch to help add variation to games.

How to use:

Add the two scripts listed below to your project.

Then add your sounds via the inspector. If you want to use pitch variations check Use Pitch on each sound item and enter a pitch range from -3.0 to 3.0 (1.0 being default).

Then it is just a matter of calling Play on the SoundRandomizer to play a sound.

Example:

    //Get sound randomizer
    var sound = GetComponent<SoundRandomizer>();
    
    //Play random sound
    sound.Play();

Script: SoundRandomizer.cs

using UnityEngine;

[RequireComponent(typeof(AudioSource))]
public class SoundRandomizer : MonoBehaviour
{

    public AudioSource Player;
    public AudioItem[] SoundItems;
    public bool Interuptable;

    private void Start ()
	{
	    if (Player == null)
	    {
	        Player = GetComponent<AudioSource>();
	    }
	}

    public void Play(ulong delay)
    {
        if (Player.isPlaying && (Player.isPlaying || !Interuptable)) return;

        var index = Random.Range(0, SoundItems.Length);
        var pitch = 1.0f;

        if(SoundItems[index].UsePitch)
            pitch = Random.Range(SoundItems[index].LowerPitch, SoundItems[index].UpperPitch);

        Player.Stop();
        Player.pitch = pitch;
        Player.clip = SoundItems[index].Clip;
        Player.Play(delay);
    }

    public void Play()
    {
        Play(0);
    }
}

Script: AudioItem.cs

using System;
using UnityEngine;

[Serializable]
public class AudioItem
{
    public AudioClip Clip;
    public float UpperPitch = 1f;
    public float LowerPitch = 1f;
    public bool UsePitch;
}
Back To posts