首页 > 解决方案 > 根据 AnalyserNode 数据修改不透明度

问题描述

我正在尝试根据音频文件的音量对某些文本的不透明度进行动画处理。

我发现这个 codepen几乎做同样的事情,但我对 JS 相当陌生,不能完全解析 Mandy 在 SCSS 和可变字体轴方面所做的事情。

我只是想在 0 和 1 之间调节不透明度。

HTML

<p class="animating-text">Lorem ipsum bacon!</p>

Javascript(我尽我所能根据链接的演示来尝试我正在尝试做的事情)

// Audio code from Ruth's Demo!! - https://codepen.io/Rumyra/pen/jomXeG
console.clear;
// create audio context and make sure it gets activated
const audioCtx = new AudioContext();
let data = new Uint8Array(2);

// create analyser 
const analyserNode = new AnalyserNode(audioCtx, {
    fftSize: 64,
    maxDecibels: -25,
    minDecibels: -60,
    smoothingTimeConstant: 0.5,
});

function getAnalyserData() {
    requestAnimationFrame(getAnalyserData);
    analyserNode.getByteFrequencyData(data);

    const minOpacity = 0;
    const maxOpacity = 1;

    const minEventValue = 0;
    const maxEventValue = 255;

    // Get the current event value
    const element = document.getElementsByClassName("animating-text");
    element.style.opacity = "0";

    if (data[0] === 255) {
        element.style.opacity = "1";
        return
    } else {
        /// not quite clear what to do here
  }
}

// set draw after stream has started
function getStreamData() {
    // pipe in analysing to getUserMedia
    return navigator.mediaDevices.getUserMedia({ audio: true, video: false })
        .then(stream => audioCtx.createMediaStreamSource(stream))
        .then(source => {
            source.connect(analyserNode);
        });
}

// resume
window.addEventListener("click", event => {
    audioCtx.resume();
    getStreamData().then(getAnalyserData);
})

标签: javascripthtmlcssaudio

解决方案


此链接中的示例https://codepen.io/LakshithaMadushan/pen/VwvxVNM

1) 注释并在 style.css 下方font-variation-settings: "yest" var(--yest); 添加 opacity: var(--yest);

2) 在 script.js 文件中,fluidAxisVariation函数的最后一行我们需要更新为element.style.setProperty(axisCustomPropertyName, newAxisValue/1000);.
(我们需要在 0 和 1 之间调整不透明度,这就是 newAxisValue 除以 1000 的原因)


推荐阅读