【小功能】Unity音频截取部分内容播放

您所在的位置:网站首页 什么音乐播放器可以截取片段 【小功能】Unity音频截取部分内容播放

【小功能】Unity音频截取部分内容播放

2024-07-09 00:27| 来源: 网络整理| 查看: 265

Unity音频截取部分播放

今天接到一个需求从Json文件里可以解析出音频起始时间和结束时间,需要根据此信息只播放某个音频文件起始时间——结束时间的音效(相当于片段)。 搜了下发现信息不是很多,而且感觉很多写的都有问题(头大,还有没注释也就算了,还是错的,啊啊啊~),后续根据网上看到的部分API按思路实现了下,代码如下:

/// /// 截取音频片段音效并播放 /// /// 截取的音频 /// 截取的开始时间 /// 截取的结束时间 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等来实现,网上也看到有这样写的,但我测试出来并没有得到我想要的效果(不知道是不可行还是我写的不对)。所以目前暂用这种方法,如果有小伙伴有其他方法,跪求大佬告知。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3