We released AmbientLooper on Unity Asset store.
This asset will generate a loop .wav file or clip from non-loop one.
Following script is a part of this asset.
attach this script in a object that contains AudioSource,
a clip in the AudioSource becomes loop clip.
Movie
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class CrossFadeLoop : MonoBehaviour
{
[Tooltip("cross fade dulation[sec]"), Range(0.1f, 5f)] public float m_crossFadeTime = 1f;
void Start()
{
AudioSource audioSrc = gameObject.GetComponent<AudioSource>();
AudioClip ac = audioSrc.clip;
float[] data = new float[ac.samples * ac.channels];
ac.GetData(data, 0);
int span = Mathf.FloorToInt(m_crossFadeTime * (float)(ac.frequency * ac.channels));
span -= (span % ac.channels);
float[] newData = CrossFade(data, span);
AudioClip newAc = AudioClip.Create("_loop_" + ac.name, newData.Length / ac.channels, ac.channels, ac.frequency, false);
newAc.SetData(newData, 0);
audioSrc.clip = newAc;
if (audioSrc.playOnAwake)
audioSrc.Play();
}
static public float[] CrossFade(float[] data, int span)
{
if (data.Length < span * 2)
return data;
float[] retData = new float[data.Length - span];
for (int i = 0; i < span; ++i)
{
float rate = (float)(i + 1) / (float)(span + 1);
retData[i] = data[i] * rate + data[data.Length - span + i] * (1f - rate);
}
for (int i = span; i < data.Length - span; ++i)
retData[i] = data[i];
return retData;
}
}
Top comments (0)