Unity音频截取部分播放
今天接到一个需求从Json文件里可以解析出音频起始时间和结束时间,需要根据此信息只播放某个音频文件起始时间——结束时间的音效(相当于片段)。
搜了下发现信息不是很多,而且感觉很多写的都有问题(头大,还有没注释也就算了,还是错的,啊啊啊~),后续根据网上看到的部分API按思路实现了下,代码如下:
/// <summary>
/// 截取音频片段音效并播放
/// </summary>
/// <param name="audioClip">截取的音频</param>
/// <param name="startTime">截取的开始时间</param>
/// <param name="endTime">截取的结束时间</param>
public void PlayAudioClipSegment(AudioClip audioClip, float startTime, float endTime)
{
// 计算截取片段的长度
float clipLength = endTime - startTime;
// 创建一个新的截取剪辑
AudioClip segment = AudioClip.Create("TempAudio", Mathf.RoundToInt(clipLength * audioClip.frequency), audioClip.channels, audioClip.frequency, false);
// 计算截取的样本数
int startSample = Mathf.RoundToInt(startTime * audioClip.frequency);
int endSample = Mathf.RoundToInt(endTime * audioClip.frequency);
int segmentLength = endSample - startSample;
// 从原始音频剪辑中复制样本到截取剪辑
float[] data = new float[segmentLength * audioClip.channels];
audioClip.GetData(data, startSample);
//数据设置进新的片段里
segment.SetData(data, 0);
// 播放截取的音频片段
audioSource.clip = segment;
audioSource.Play();
}
目前发现这种方法可行,但不清楚有没有更好或更便捷的方法,我尝试过
audioSource.time = startTime; audioSource.SetScheduledEndTime等来实现,网上也看到有这样写的,但我测试出来并没有得到我想要的效果(不知道是不可行还是我写的不对)。所以目前暂用这种方法,如果有小伙伴有其他方法,跪求大佬告知。