- Home /
Play a segment in a audio file
I am working on a music game which requires me to play small audio clips very quickly. At the moment I play the clips using PlayOneshot.
I am thinking of putting all the clips in to a single audio clip and jump to different positions in that clip.
Is this a good idea?
So I tried the following as a test. I go to the 90 beat at the beginning. And each beat I jump to a random location.
But the output is jumble of sounds can’t make out anything.
Can anyone suggest a solution ?
void Start ()
{
source = gameObject.GetComponent<AudioSource>();
source.clip = clip;
samplePeriod = 60f * clip.frequency / 110.0f;
nextBeatSample = clip.frequency;
numberOfBests = (int)(clip.length*clip.frequency/samplePeriod);
source.time = (float)(clip.length * 90 / numberOfBests);
source.Play();
StartCoroutine(BeatCheck());
}
private IEnumerator BeatCheck()
{
while (source.isPlaying)
{
currentSample = (double)AudioSettings.dspTime * clip.frequency;
if (currentSample >= nextBeatSample)
{
nextBeatSample += samplePeriod;
source.time = (float)(clip.length * Random.Range(numberOfBests/4, numberOfBests/2) / numberOfBests);
}
yield return new WaitForSeconds(loopTime / 1000f);
}
}
...why exactly did you combine the audio into one big file to start with?
i thought it would be more efficient to jump to different locations of the file ins$$anonymous$$d of playing different files.
I have around 100 small files
I mean, it might be a tiny bit more efficient in the finished project... maybe.
But is it really worth the trouble? That introduces so many new points of failure, at least in my opinion, that the costs outweigh the benefits.
Answer by Loui_Studios · Jan 28, 2017 at 03:22 PM
I see you're already using AudioSource.time.
You say that you jump to a random point in the clip every beat and the sounds are jumbled?
Either your timing between beats is off, and the sound clips are switching too fast, or your positioning is off, and you're playing the wrong part of the file.
Try rewriting the timer, and if that doesn't work, double check to make sure you're playing the right part of the track.
If that doesn't work, I recommend splitting the one big AudioClip into lots of small ones. Put all of the small AudioClips into an AudioClip array, and play a random clip each beat. It's the easiest way!