javascript – 交叉淡化HTML5音频逻辑
作者:互联网
我正在尝试交叉淡化HTML5音频(不是webaudio)并使用等功率交叉淡化曲线:
var gain1 = Math.cos(x * 0.5 * Math.PI);
var gain2 = Math.cos((1.0 - x) * 0.5 * Math.PI);
但是我遇到了一些逻辑问题.
假设我有两个声音实例,Sound1& Sound2,都有相同的来源.
如果Sound1以全音量(1.00)播放,则很容易交叉淡入淡出它们,我想在交叉渐变后以最大音量播放Sound2.我只需要将x的值从0循环到100并将gain1设置为Sound1的音量,并将gain2设置为Sound2的音量.
但是如果我现在以0.75的音量播放Sound1并且我希望在交叉渐变之后最终以相同的音量播放Sound2.
如何计算x的正确范围?从哪里开始以及在哪里停止循环?
解决方法:
您必须乘以计算的增益:
var original_gain1 = 1.0;
var original_gain2 = 0.75;
var final_gain1 = original_gain1 * Math.cos(x * 0.5 * Math.PI);
var final_gain2 = original_gain2 * Math.cos((1.0 - x) * 0.5 * Math.PI);
简单交叉淡入淡出所需要的是异步循环.使用以下代码,您可以启动循环以将x从0增加到1,然后返回.这些函数将在每个周期调用updateGains.
var x = 0;
var crossfade_speed = 0.05;
function crossfadeTo1()
{
// if we havent reached 1.0
if ( x<1.0 )
{
// increase x
x += crossfade_speed;
// continue the asynchronous loop after 200ms (it will update volumes 5 times a second)
setTimeout( crossfadeTo1, 200 );
}
else
{
// set x the maximum ( we can go over 1.0 in the loop )
x = 1.0;
// we dont call the function again, so the loop stops
}
// call your function with x to update gains
updateGains( x );
}
function crossfadeTo0()
{
// if we havent reached 0.0
if ( x>0.0 )
{
// decrease x
x -= crossfade_speed;
// continue the asynchronous loop after 200ms (it will update volumes 5 times a second)
setTimeout( crossfadeTo0, 200 );
}
else
{
// set x the minimum ( we can go under 0.0 in the loop )
x = 0.0;
// we dont call the function again, so the loop stops
}
// call your function with x to update gains
updateGains( x );
}
标签:javascript,html5,html5-audio,html 来源: https://codeday.me/bug/20190623/1272694.html