
上QQ阅读APP看书,第一时间看更新
How to do it...
To create a music-loop manager, do the following:
- Create a new Unity 3D project and import the provided sound clip files.
- Create four GameObjects in the scene containing an AudioSource component linked to different AudioClip loops from the 140 bpm files provided. This can be done in a single step by dragging the music clip from the Project panel into either the Hierarchy or Scene panels.
- In the Inspector, uncheck the Play On Awake parameter for all four AudioSource components (so they don't start playing until we tell them to).
- Add a new empty GameObject named musicScheduler to the scene.
- Create a C# script class, LoopScheduler, in a new folder, _Scripts, containing the following code, and add an instance as a scripted component to the musicScheduler GameObject:
using UnityEngine; public class LoopScheduler : MonoBehaviour { public float bpm = 140.0F; public int numBeatsPerSegment = 16; public AudioSource[] audioSources = new AudioSource[4]; private double nextEventTime; private int nextLoopIndex = 0; private int numLoops; private float numSecondsPerMinute = 60F; private float timeBetweenPlays; void Start() { numLoops = audioSources.Length; timeBetweenPlays = numSecondsPerMinute / bpm * numBeatsPerSegment; nextEventTime = AudioSettings.dspTime; } void Update() { double lookAhead = AudioSettings.dspTime + 1.0F; if (lookAhead > nextEventTime) StartNextLoop(); PrintLoopPlayingStatus(); } private void StartNextLoop() { audioSources[nextLoopIndex].PlayScheduled(nextEventTime); nextEventTime += timeBetweenPlays; nextLoopIndex++; if (nextLoopIndex >= numLoops) nextLoopIndex = 0; } private void PrintLoopPlayingStatus(){ string statusMessage = "Sounds playing: "; int i = 0; while (i < numLoops) { statusMessage += audioSources[i].isPlaying + " "; i++; } print(statusMessage); } }
- With the musicScheduler GameObject selected in the Hierarchy, drag each of the music loop GameObjects into the four available slots for the AudioSources public array variable in the Loop Scheduler (Script) component:

- Run the scene – each clips should start in turn after the same time delay. If you chose one or two longer clips, they will continue playing while the next clip begins – all overlapping perfectly since they are all 140 bpm sound clips.