淡入淡出 HTML5 音频逻辑

uns*_*ska 5 html javascript html5-audio

我正在尝试交叉淡入淡出 HTML5 音频(不是网络音频)并使用等功率交叉淡入淡出曲线:

var gain1 = Math.cos(x * 0.5 * Math.PI);
var gain2 = Math.cos((1.0 - x) * 0.5 * Math.PI);
Run Code Online (Sandbox Code Playgroud)

但我对此有一些逻辑问题。

假设我有两个声音实例,Sound1 和 Sound2,它们都有相同的源。

如果 Sound1 以全音量播放 ( 1.00),并且我想在交叉淡入淡出后最终以全音量播放 Sound2,则可以轻松交叉淡入淡出它们。我只需要将x的值从0循环到100并将gain1设置为Sound1的音量并将gain2设置为Sound2的音量。

但是,如果我当前正在以0.75相同的音量播放 Sound1,并且希望在交叉淡入淡出后最终以相同的音量播放 Sound2,该怎么办?

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

Lás*_*nál 5

您必须乘以计算出的增益:

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);
Run Code Online (Sandbox Code Playgroud)

简单的交叉淡入淡出需要的是异步循环。使用以下代码,您可以启动循环将 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 );     
}    
Run Code Online (Sandbox Code Playgroud)