我编写了一个脚本,可以播放数组中的随机音频文件。但我不知道如何在文件末尾淡出当前播放的音频并淡入新的音频文件。下面是代码。我现在使用的音频文件是 mp3 文件,我计划切换到波形文件。以及对此的任何建议
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;
}
}