• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Cbjfan1 · Aug 24, 2012 at 05:33 PM · audiorandomplay

Randomly play audio

Hi everyone. I am making a game, and it feels really quiet. I am trying to make it so the game randomly places ambient that I have to make it more realistic. Can somebody help me with this?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by AlucardJay · Aug 24, 2012 at 06:56 PM

Set up a counter and a random time to play a track, then choose a random track from a list of tracks =]

 #pragma strict
 @script RequireComponent(AudioSource)
 
 public var music1 : AudioClip;
 public var music2 : AudioClip; 
 public var music3 : AudioClip; 
 private var randomMusic : int = 0;
 private var randomTime : float = 120.0;
 private var timeCounter : float = 0.0;
 
 function Update ()
 {
     if(timeCounter  > randomTime)
     {
        randomTime = Random.Range(60.0, 180.0);
        timeCounter = 0.0;
        audio.Stop();
        ChooseMusic();
        audio.Play();
     }
 
     timeCounter += Time.deltaTime;
 }
 
 function ChooseMusic()
 {   
     randomMusic = Random.Range(0, 3);
 
     switch (randomMusic)
     {
       case 0: 
         audio.clip = music1; 
         break;
       case 1: 
         audio.clip = music2; 
         break;
       case 2: 
         audio.clip = music3; 
         break;
     }
 
     Debug.Log( "Current Clip = music" + (randomMusic + 1) );
 }

======================================================================================

I have updated this answer with a new setup that fades and blends between tracks. It also doesn't repeat the same track twice.

First to set up :

  • create an empty gameObject, attach the below script

  • create 2 empty gameObjects, attach an AudioSource to each one, make them both a child of the object with the script

  • set the AudioSources to NOT play on awake. Optional set loop to True (your choice)

See Image :

alt text

Now on the object with the script, drag and drop in the different Audio Clips (minimum of 2)

The other variables are as follows :

  • playTimeMin : time in seconds, minimum time before changing tracks

  • playTimeMax : time in seconds, maximum time before changing tracks

  • transitionFadeTime : time in seconds, time it takes for fade to complete

  • transitionFadeVolume : volume between 0 and 1, volume the current track gets to before blending in the new track

So the tracks change between a random time between playTimeMin and playTimeMax.

transitionFadeTime is over how long the time the fade takes place, this also then affects the rate of fade.

transitionFadeVolume works best with a value between 0.001 and 0.5 :

  • at 0.001, the old track completely fades out before the new track fades in

  • at 0.5, the old track fades down to half volume, while the new track fades up to half volume. The old track fades completely out while the new track fades up to full volume

  • at 1, the old track will instantly stop, and the new track will play at full volume

Here is the script :

 //------------------------------//
 //  MusicTransitionFader.js     //
 //  Written by Alucard Jay      //
 //  2/11/2014                   //
 //------------------------------//
 
 #pragma strict
 
 import System.Collections.Generic;
 
 
 public var musicTracks : List.< AudioClip >; // drag and drop audio clips in Inspector * MINIMUM 2 clips *
 
 public var playTimeMin : float = 60; // time in seconds, minimum time before changing tracks
 public var playTimeMax : float = 180; // time in seconds, maximum time before changing tracks
 
 public var transitionFadeTime : float = 3; // time in seconds, time it takes for fade to complete
 public var transitionFadeVolume : float = 0.25; // volume between 0 and 1, volume the current track gets to before blending in the new track
 
 
 private var audioSources : AudioSource[];
 private var currentSource : int = 0;
 
 private var musicTracksAvailable : List.< int >;
 private var currentTrack : int = 0;
 
 private var isFading : boolean = false;
 
 private var timer : float = 0;
 private var timerMax : float = 60;
 
 
 //  Persistant Functions
 //    ----------------------------------------------------------------------------
 
 
 function Awake() 
 {
     // NOTE : this object must have 2 child objects,
     // each with an AudioSource component to work
     audioSources = GetComponentsInChildren.< AudioSource >();
 }
 
 
 function Start() 
 {
     // dummy select current track playing 
     // (so its possible that musicTracks[0] could be selected as first track to play)
     currentTrack = Random.Range( 0, musicTracks.Count );
     
     // set timer over max so first update is set to fading
     // after resetting values in CheckTrackTimer()
     timer = timerMax + 1;
 }
 
 
 function Update() 
 {
     timer += Time.deltaTime;
     
     switch ( isFading )
     {
         case false :
             CheckTrackTimer();
         break;
         
         case true :
             FadeTransition();
         break;
     }
 }
 
 
 //  Other Functions
 //    ----------------------------------------------------------------------------
 
 
 function SelectNextTrack() 
 {
     // create a list of available tracks to choose from
     // (so the current track is not chosen and repeated)
     musicTracksAvailable = new List.< int >();
     
     for ( var t : int = 0; t < musicTracks.Count; t ++ )
     {
         musicTracksAvailable.Add( t );
     }
     
     //remove current track from the list
     musicTracksAvailable.RemoveAt( currentTrack );
     
     // pick a new random track
     currentTrack = musicTracksAvailable[ Random.Range( 0, musicTracksAvailable.Count ) ];
     
     // assign track to AudioSource that is NOT currently playing
     audioSources[ ( currentSource + 1 ) % 2 ].audio.Stop();
     audioSources[ ( currentSource + 1 ) % 2 ].audio.clip = musicTracks[ currentTrack ];
     audioSources[ ( currentSource + 1 ) % 2 ].audio.volume = 0;
 }
 
 
 function CheckTrackTimer() 
 {
     if ( timer > timerMax )
     {
         // reset timer, set new max time to next transition
         timer = 0;
         timerMax = Random.Range( playTimeMin, playTimeMax );
         
         SelectNextTrack();
         
         isFading = true;
     }
 }
 
 
 function FadeTransition() 
 {
     var fadeIn : float = 0;
     
     // calculate the fade Out volume
     var fadeOut : float = 1.0 - ( timer / transitionFadeTime );
     fadeOut = Mathf.Clamp01( fadeOut );
     
     audioSources[ currentSource ].audio.volume = fadeOut;
     
     
     // if fadeOut is low enough, start playing the new track and fade it in
     
     if ( fadeOut < ( transitionFadeVolume * 2.0 ) )
     {
         // is the next track playing yet?
         if ( !audioSources[ ( currentSource + 1 ) % 2 ].isPlaying )
         {
             audioSources[ ( currentSource + 1 ) % 2 ].audio.Play();
         }
         
         // calculate the fade In volume
         fadeIn = timer;
         // minus how long for the other source to reach transitionFadeVolume
         fadeIn -= ( 1.0 - transitionFadeVolume ) * transitionFadeTime;
         // add how long for this source to reach transitionFadeVolume
         fadeIn += transitionFadeVolume * transitionFadeTime;
         // normalize by dividing by fade time
         fadeIn /= transitionFadeTime;
         
         fadeIn = Mathf.Clamp01( fadeIn );
         
         audioSources[ ( currentSource + 1 ) % 2 ].audio.volume = fadeIn;
     }
     
     
     // check if next track has fully faded in
     if ( fadeIn == 1 )
     {
         // stop the old audio from playing
         audioSources[ currentSource ].audio.Stop();
         
         // set new current AudioSource index
         currentSource = ( currentSource + 1 ) % 2;
         
         // reset timer
         timer = 0;
         
         isFading = false;
     }
     
     //Debug.Log( "fadeOut = " + fadeOut + " : fadeIn = " + fadeIn );
 }



musicfadersetup.jpg (128.9 kB)
Comment
Add comment · Show 6 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Hyperactive · Feb 08, 2014 at 09:20 PM 0
Share

As usual @alucardj you have the best scripts. I'm publishing the first version of my latest game on Oculus Share today thanks to all your tutorials and help on these forums. $$anonymous$$eep it up and keep coding! :)

avatar image AlucardJay · Feb 11, 2014 at 05:36 AM 0
Share

Thank you so much for your nice response, I'm really glad my answers have helped you. This inspired me to update this answer with a more complex script.

The new edit now fades the tracks in and out rather than a clash of suddenly stopping a track and playing the new one. This requires a bit of setting up, all details are in the edited answer.

Thanks again, and Happy Coding =]

avatar image Hyperactive · Feb 11, 2014 at 11:12 AM 0
Share

Brilliant! I was just working on fading in/out audio tracks in my audio zones last night. It's not easy...but your code is fantastic. All the comments are most helpful, I can read through your code and I learn so much while I do so. $$anonymous$$y game is going to be TERRIFYING now that the audio sneaks up on you (even though a good audio burst is perfect for a jump scare!). Thanks again.

avatar image serkanos · May 26, 2015 at 04:08 AM 0
Share

very thnks man Very helpfull.

avatar image CL3NRc2 · Jun 18, 2019 at 12:55 AM 0
Share

seriously? this script is broken all to hell! im getting 32 errors with this single script! thanks, but no thanks. im not wasting my time on fixing errors that just wont go away.

avatar image Owen-Reynolds CL3NRc2 · Jun 18, 2019 at 02:40 AM 0
Share

It's in UnityScript, which was discontinued a while ago, but used to be the preferred language. It ran just fine before. Now, the best you can do is use the ideas in it and translate to C#.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

12 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Audio Clip Plays 1 turn too late 1 Answer

Audio source problem 2 Answers

How do I get Button to play a random sound in Unity 5.0? 2 Answers

Using High Pass Filter with script 2 Answers

How to string multiple audio clips together 1 Answer

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges