2015-08-22 99 views
3

我试图交叉衰减HTML5音频(不webaudio),并使用相同功率的淡入淡出曲线:淡入淡出HTML5音频逻辑

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的音量。

但是如果我现在正在播放Sound1的音量为0.75,我想在交叉淡入淡出之后以相同音量播放Sound2。

如何计算x的正确范围?从何处开始以及在何处停止循环?

回答

4

您必须将计算出来的增益:

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);  
}