unity开发,有需求背景音乐可以切换,通过代码获取AudioClip,给音频的clip进行赋值,替换新的音乐clip就可以,正常逻辑没问题,在Editor模式下,执行逻辑
private void bgmicCallback(AudioClip aclip)
{
GFDebug.Log($"加载背景音乐加载回来了 !!!!! "+ aclip.name);
m_bgAs.clip = aclip;
m_bgAs.loop = true;
m_bgAs.Play();
}
Editor和windos平台下是没问题的, 但是发布webgl后,执行这里汇报错误: Exception: TypeError: AudioBufferSourceNode.start: Argument 2 is not a finite floating-point value.
查阅了很多资料,终于找到了原因,这一定是Unity错误......我认为。
它使用@hallonavi解决方案。不要在构建后进行更改,而是更改源代码。
1. 找到 Audio.js 文件 “Unity2021.3.6f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\lib/Audio.js”
2.搜索函数 “channel.playSoundClip = function (soundClip, startTime, startOffset)”
3.添加以下内容,
/**
* Play a sound clip on the channel
* @param {UncompressedSoundClip|CompressedSoundClip} soundClip
* @param {number} startTime Scheduled start time in seconds
* @param {number} startOffset Start offset in seconds
*/
channel.playSoundClip = function (soundClip, startTime, startOffset) {
try {
var self = this;
this.source = soundClip.createSourceNode();
this.setupPanning();
// Setup on ended callback
this.source.onended = function () {
self.disconnectSource();
if (self.callback) {
dynCall("vi", self.callback, [self.userData]);
}
};
this.source.loop = this.loop;
this.source.loopStart = this.loopStart;
this.source.loopEnd = this.loopEnd;
if(isNaN(startTime)){startTime =0;}
if(isNaN(startOffset)){startOffset =0;}
this.source.start(startTime, startOffset);
this.source.scheduledStartTime = startTime;
this.source.playbackStartTime = startTime - startOffset / this.source.playbackRate.value;
this.source.setPitch(this.pitch);
} catch (e) {
// Need to catch exception, otherwise execution will stop on Safari if audio output is missing/broken
console.error("Channel.playSoundClip error. Exception: " + e);
}
};
所示:
if(isNaN(startTime)){startTime = 0;}
if(isNaN(startOffset)){startOffset = 0;}
注意:您需要为您正在处理的 Unity 版本做。
这样在打包,webgl运行切换音频就可以了。