HTML5 <音频>淡入淡出播放 [英] HTML5 <audio> playback with fade in and fade out

查看:14
本文介绍了HTML5 <音频>淡入淡出播放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在带有淡入和淡出周期的随机位置开始和停止 HTML5 播放,以平滑收听体验.

I'd like to start and stop HTML5 playback in a random position with fade in and fade out periods to smooth the listening experience.

为此存在什么样的机制?使用 setTimeout() 手动增大音量?

What kind of mechanisms exists for this? Manually ramp up the volume with setTimeout()?

推荐答案

jQuery 方式...

The jQuery way...

$audio.animate({volume: newVolume}, 1000);

其中 $audio 是一个 jQuery 包装的音频元素,newVolume 是一个介于 0 和 1 之间的双精度值.

where $audio is a jQuery-wrapped audio element and newVolume is a double between 0 and 1.

该元素的有效媒体音量是音量,相对于 0.0 到 1.0 的范围进行解释,0.0 表示静音,1.0 表示最响亮的设置,介于两者之间的值随着响度的增加而增加.范围不必是线性的.http://www.w3.org/html/wg/drafts/html/master/embedded-content.html#effective-media-volume

The element's effective media volume is volume, interpreted relative to the range 0.0 to 1.0, with 0.0 being silent, and 1.0 being the loudest setting, values in between increasing in loudness. The range need not be linear. http://www.w3.org/html/wg/drafts/html/master/embedded-content.html#effective-media-volume

人们正在发布普通的 JavaScript 实现,所以我将发布一个保留 jQuery 摆动动画的普通 TypeScript(如果你想在 JavaScript 中运行它,只需去掉类型信息).免责声明,这是完全未经测试的:

People are posting vanilla JavaScript implementations, so I'll post a vanilla TypeScript one that preserves the jQuery swing animation (just strip out the type info if you want to run this in JavaScript). Disclaimer, this is completely untested:

export async function adjustVolume(
    element: HTMLMediaElement,
    newVolume: number,
    {
        duration = 1000,
        easing = swing,
        interval = 13,
    }: {
        duration?: number,
        easing?: typeof swing,
        interval?: number,
    } = {},
): Promise<void> {
    const originalVolume = element.volume;
    const delta = newVolume - originalVolume;

    if (!delta || !duration || !easing || !interval) {
        element.volume = newVolume;
        return Promise.resolve();
    }

    const ticks = Math.floor(duration / interval);
    let tick = 1;

    return new Promise(resolve => {
        const timer = setInterval(() => {
            element.volume = originalVolume + (
                easing(tick / ticks) * delta
            );

            if (++tick === ticks + 1) {
                clearInterval(timer);
                resolve();
            }
        }, interval);
    });
}

export function swing(p: number) {
    return 0.5 - Math.cos(p * Math.PI) / 2;
}

这篇关于HTML5 &lt;音频&gt;淡入淡出播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆