- Home /
Multiple gapless sound loops from one AudioSource (C#)
I have seen many questions about using multiple AudioSources but in my case, I want to use just one AudioSource, and one script controlling it. I have assigned 3 sound loops and I want to loop them without gaps all at once from one AudioSource, as well as stop and play individual sound loop with different individual volumes. Here's where I am right now:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class Sound : MonoBehaviour {
AudioSource audioSource;
public AudioClip audioClip1;
public AudioClip audioClip2;
public AudioClip audioClip3;
[Range (0, 1)] public float audioClipVolume1;
[Range (0, 1)] public float audioClipVolume2;
[Range (0, 1)] public float audioClipVolume3;
void Start () {
audioSource = GetComponent<AudioSource> ();
audioSource.loop = true;
}
void Update () {
//How do I loop all 3 audio clips without gaps?
//Tried using PlayOneShot
//Checking if it is playing and playing it again creates gaps
//Also, if one sound loop is shorter than the other soundloops, will wait untill
//other sound loops finished to start playing again...
if (!audioSource.isPlaying) {
audioSource.PlayOneShot (audioClip1, audioClipVolume1);
audioSource.PlayOneShot (audioClip2, audioClipVolume2);
audioSource.PlayOneShot (audioClip3, audioClipVolume3);
}
//Tried changing clip
//AudioSource can load only one clip, but allows for gapless looping
audioSource.clip = audioClip2;
audioSource.volume = audioClipVolume2;
if (!audioSource.isPlaying) {
audioSource.Play ();
}
}
}
Answer by DemSec · Aug 10, 2016 at 05:13 AM
I took SuperStarPL's advice and created an Audio Source for each sound.
Answer by SuperStarPL · Jun 22, 2016 at 03:59 PM
If you want seamless/gap free transitions, you should use 3 Audio Sources playing at the same time, with only one's volume set to > 0. Then, you crossfade volumes using Lerp or something similar.
Doesn't having multiple Audio Sources slows down the game more than scripting it out? Also, could I have all 3 audio sources on one object and differentiate between them? if so, could you give me a C# script example? Thanks!
Your answer
Follow this Question
Related Questions
Looping an audio while holding "shift key" 1 Answer
Play sound effect throughtout an entire animation clip 1 Answer
[Rhytm game] How to spawn on exact time of music? 3 Answers
How to get C# Array to Load into Audio Source 0 Answers
AudioClip stuttering while loop is OFF and not using function Update? 1 Answer