首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >交叉衰落HTML5音频逻辑

交叉衰落HTML5音频逻辑
EN

Stack Overflow用户
提问于 2015-08-22 10:34:50
回答 1查看 2.4K关注 0票数 5

我试图交叉淡出HTML5音频(而不是网络音频),并使用等功率交叉衰落曲线:

代码语言:javascript
复制
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卷上播放Sound2,并且希望在交叉淡出之后以相同的音量播放Sound2,那该怎么办?

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-22 22:15:34

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

代码语言:javascript
复制
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。

代码语言:javascript
复制
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 );     
}    
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32155105

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档