我编写了一个脚本,从数组中随机播放音频文件。但是我不知道如何在文件末尾淡出当前播放的音频,并在新的音频文件中淡出。下面是代码。我现在使用的音频文件是mp3文件,我计划切换到wave文件。有什么建议吗
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using Random = UnityEngine.Random;
public class BackGroundAudio : MonoBehaviour
{
public AudioSource audioSource;
public AudioClip[] audioClipsArray;
public String FileName;
// Start is called before the first frame update
void awake()
{
audioSource = GetComponent<AudioSource>();
}
void Start()
{
}
// Update is called once per frame
void Update()
{
if (!audioSource.isPlaying)
{
PlayRandom();
}
}
void PlayRandom()
{
audioSource.clip=audioClipsArray[Random.Range(0,audioClipsArray.Length)];
audioSource.clip =trimSilence(audioSource.clip);
audioSource.PlayOneShot(audioSource.clip);
}
AudioClip trimSilence(AudioClip inputAudio, float threshold = 0.05f)
{
// Copy samples from input audio to an array. AudioClip uses interleaved format so the length in samples is multiplied by channel count
float[] samplesOriginal = new float[inputAudio.samples * inputAudio.channels];
inputAudio.GetData(samplesOriginal, 0);
// Find first and last sample (from any channel) that exceed the threshold
int audioStart = Array.FindIndex(samplesOriginal, sample => sample > threshold),
audioEnd = Array.FindLastIndex(samplesOriginal, sample => sample > threshold);
// Copy trimmed audio data into another array
float[] samplesTrimmed = new float[audioEnd - audioStart];
Array.Copy(samplesOriginal, audioStart, samplesTrimmed, 0, samplesTrimmed.Length);
// Create new AudioClip for trimmed audio data
AudioClip trimmedAudio = AudioClip.Create(inputAudio.name, samplesTrimmed.Length / inputAudio.channels, inputAudio.channels, inputAudio.frequency, false);
trimmedAudio.SetData(samplesTrimmed, 0);
return trimmedAudio;
}
}
这样的东西应该做到这一点,你可以用音频混频器做更好的解决方案,但我相信这是最低的努力/最简单的实现。
换句话说:当你开始一个剪辑,它会设置audioSource的音量从0到1超过FADE_TIME_SECONDS
秒。然后在同一时间,我们开始一个协程延迟与剪辑的长度减去FADE_TIME_SECONDS
,并做同样的,但从1到0,这为下一个轨道设置,开始音量在0和淡出。
在代码:
const float FADE_TIME_SECONDS = 5;
void PlayRandom()
{
StartCoroutine(FadeIn());
audioSource.clip = audioClipsArray[Random.Range(0,audioClipsArray.Length)];
audioSource.clip = trimSilence(audioSource.clip);
audioSource.PlayOneShot(audioSource.clip);
StartCoroutine(FadeOut(audioSource.clip.length - FADE_TIME_SECONDS));
}
IEnumerator FadeOut(float delay)
{
yield return new WaitForSeconds(delay);
var timeElapsed = 0;
while (audioSource.volume > 0)
{
audioSource.volume = Mathf.Lerp(1, 0, timeElapsed / FADE_TIME_SECONDS);
timeElapsed += Time.deltaTime;
yield return;
}
}
IEnumerator FadeIn()
{
var timeElapsed = 0;
while (audioSource.volume < 1)
{
audioSource.volume = Mathf.Lerp(0, 1, timeElapsed / FADE_TIME_SECONDS);
timeElapsed += Time.deltaTime;
yield return;
}
}