Adjust transparency according to the information extracted from the AnalyserNode

Currently, I am exploring ways to animate text opacity based on the volume of an audio file.

While browsing online, I came across this specific codepen example, which showcases a similar concept. However, as I am relatively new to JavaScript, I find it challenging to understand Mandy's implementation involving SCSS and Variable Font axis.

My main objective is to smoothly alter the opacity of text between 0 and 1.

HTML

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

Javascript (I have made an attempt at replicating the desired functionality based on the provided demo)

// Here is some audio code inspired by Ruth's Demo!! - https://codepen.io/Rumyra/pen/jomXeG
console.clear;
// Initializing the audio context and ensuring its activation
const audioCtx = new AudioContext();
let data = new Uint8Array(2);

// Creating an analyser node 
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;

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

    if (data[0] === 255) {
        element.style.opacity = "1";
        return
    } else {
        /// Unclear what action to take here
  }
}

// Obtaining stream data after starting
function getStreamData() {
    // Connecting analysis to getUserMedia
    return navigator.mediaDevices.getUserMedia({ audio: true, video: false })
        .then(stream => audioCtx.createMediaStreamSource(stream))
        .then(source => {
            source.connect(analyserNode);
        });
}

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

Answer №1

For a demonstration, check out the code sample provided at https://codepen.io/LakshithaMadushan/pen/VwvxVNM

1) Make sure to uncomment

font-variation-settings: "yest" var(--yest);
and then include opacity: var(--yest); right below it in the style.css file.

2) At the end of the fluidAxisVariation function in the script.js file, update the last line to read as follows:

element.style.setProperty(axisCustomPropertyName, newAxisValue/1000);
.
(This adjustment is necessary to adjust opacity values between 0 and 1 by dividing newAxisValue by 1000)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for incorporating code to calculate the total price and append it to the orderMessage

I am seeking help with this program that my professor assigned to me. The instructions marked by "//" are the ones I need to implement in the code, but I'm struggling to understand how to proceed. Any assistance would be greatly appreciated, even just ...

Create a stylish layout with two div elements positioned side by side using flexbox for a responsive design

Struggling with my portfolio website, I encountered a challenge. I attempted to place two divs side by side, each containing text and an image. While the initial setup was simple, trying to make it responsive using flexbox has proven to be quite frustratin ...

"Varying hues on various displays: Exploring RGB values and CSS for video color

Recently, I designed a webpage with a background-color of #f4afac. The video embedded in this page also features the same background color throughout, creating a seamless blend with no visible edges. On one screen, the colors appear perfectly consistent. ...

Steps for styling an AngularJS Popup:1. Determine the desired appearance for

I have some code that displays a popup when clicked, along with its automatically generated CSS. I want to be able to make changes to the CSS by adding IDs or classes to it. How can I assign IDs or classes to this element so that I can easily target them f ...

What is the best way to resize an image in HTML based on a percentage of its height?

Within my HTML code, I have a PNG image that has been adjusted in size using CSS: .adjust-image { border:1px solid #021a40; display: block; width: auto; max-width: 100%; max-height: 1000px; } .img-container { position: relative; } ...

Analyzing viewer engagement by monitoring the duration of video watched using JavaScript

I need a way to monitor video views for individual users, using a table in the database called Viewings. Each viewing is associated with both a user and a video, and keeps track of the duration watched as well as the percentage of the video completed. Whe ...

Ways to modify Angular pipe without specifying data types

I am in the process of extracting an Angular pipe from an application to a library. The current pipe is tied to specific types, but I want to change it to use generic types while maintaining type safety. Original Pipe: import { Pipe, PipeTransform } fr ...

The isolate scope variable is becoming undefined within the link function

When working with a directive that takes a data object and a function in its isolate scope, I encountered an issue. Inside the link function, I declared a method to be triggered on a button click event. The problem is that while the value passed to the me ...

Facing a problem with querying interfaces and types in TypeScript

My goal is to pass a variable to an RTK Query API service that uses a typescript interface: const device_id: unique symbol = Symbol(props.id); const { data: device, isFetching, isLoading, } = useGetAssetsByIdQuery(device_id, { pollingInterv ...

I am attempting to access an Angular variable using JavaScript, but unfortunately, I am encountering some issues

I'm currently implementing the following code: window.onload=function(){ var dom_el2 = document.querySelector('[ng-controller="myCtrl"]'); var ng_el2 = angular.element(dom_el2); var ng_el_scope2 = ng_el2.scope(); console.log ...

Centered on the page vertically, two distinct sentences gracefully align without overlapping, effortlessly adjusting to different screen sizes

I had no trouble centering horizontally but I'm struggling with vertical alignment. I want these two sentences to be positioned in the middle of the page, regardless of device size. I attempted using vertical-align without success and then tried posit ...

Steps to trigger a Bootstrap modal when the user clicks anywhere on the webpage

I need assistance with setting up a Bootstrap dialogue modal to open at the clicked position on a mousedown event when a user interacts with the page. Despite my attempts, the dialogue modal is not opening where it should be. Here's what I've tri ...

Unable to transfer card from the top position in the screen

Utilizing Tailwind (flowbite) for the frontend of my project, I encountered an issue where the Navbar was overlapping the Card. I attempted using mt-8 to resolve the problem, but it did not yield significant changes. What adjustments should I make to achi ...

Display data in a template upon receiving a response from the server

Hello, I am currently in the process of developing my very first Angular application and could use some assistance. Specifically, I am working on a component that serves as an image search box. When a user inputs a search query, a request is sent to an API ...

Transform basic text into nested JSON structure with JavaScript

There is a plain string in my possession which contains various conditions. const optionString = '{2109} AND ({2370} OR {1701} OR {2702}) AND {1234} AND ({2245} OR {2339})'; The goal is to transform this string into an object structured as foll ...

Saving Arrays through an Input Form in JavaScript

I am working with an HTML form that looks like the following: <div class="form-group"> <label for="first_name">1st Name</label> <input type="text" id="first_name" placeholder="First Name" class="form-control"/> </div> ...

Uploading photos to Firebase storage using React Native

Could you please assist me in identifying my mistake here? I saw it being done in a video. The error message I am encountering is: TypeError: undefined is not an object (evaluating 'media.cancelled') const [isUploading, setIsUploading] = useS ...

Navigate through a series of div elements using Jquery

I need help figuring out how to make the window scroll between different divs in a sequence. The issue is that my current code only works for one specific div at a time. $('.down_arrow').click(function(e){ $('html, body') ...

Accessing JS code from HTML is not possible in React

Attempting to create a list using React, I have utilized the module found here: https://github.com/pqx/react-ui-tree I am currently testing out the sample application provided in this link: https://github.com/pqx/react-ui-tree/blob/gh-pages/example/app.js ...

Styling errors with jQuery validation

How can I remove the borders in ul > li elements? Here is my current setup: errorLabelContainer: $("ul", $('div.error')), wrapper: 'li', errorContainer: $('div.error'), I have tried the following: div.message{ backgr ...