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

Emails cannot display CSS styles

I'm experiencing a problem with my email messages not reading the CSS styles, regardless of whether I use inline CSS or not. I have tried everything but still can't figure out the issue. Can anyone assist me? $firstname = $row['firstname&ap ...

Creating an XPATH Selector with SCRAPY

Having trouble retrieving the product name from a webpage: Struggling to locate XPATH that delivers a useful, specific result. Apologies for my initial question being quite basic :( class V12Spider(scrapy.Spider): name = 'v12' start_ur ...

The transparency of my navbar renders it elegant, yet I desire to imbue the toggle background with a vibrant hue

I'm facing an issue with the transparent Navbar I built in Bootstrap 5. On mobile toggle view, the navigation links are getting lost within the text of the hero image. To resolve this, I want to keep the main navigation bar transparent and change the ...

Calculating Object's Position with Velocity Results in NaN

My goal is to have my canvas arcs (representing dog objects) follow the mouse cursor's movements. However, when I check the position or velocity of the objects using console.log, it shows Vector{ x: NaN, y: NaN} A strange observation is that if I di ...

Implementing Click-Activated Scroll-to-Div Feature in React

I need to implement a scroll-to-div feature in my React App. However, the current structure of my app is preventing me from passing refs as props correctly, making it challenging to utilize ref.current.scrollIntoView(). The layout of my code looks like th ...

Inquiring about the Model component within the MVC architecture in a web application created with NodeJs and integrated with

As a beginner in NodeJs, I am venturing into creating web applications using the express framework and MySQL. Understanding that in MVC architecture, views are represented by *.ejs files, controllers handle logic, and models interact with the database. Ho ...

Background image not displaying in new tab after Chrome extension installation

I have been developing a Chrome extension that alters the background image of a new tab. However, I have encountered an issue where the background image doesn't change the first time the extension is loaded. This problem has also occurred very occasi ...

Error message: Unhandled error: The function Role.Create is not defined

I'm encountering an issue with a ".create is not a function" error while trying to repopulate my database upon restarting nodemon. Previously, everything was functioning well and all the tables were populated successfully. However, I keep receiving th ...

What is the best way to create a unit test for a function that calls upon two separate functions?

When testing the getAppts function within this module, the correct way to evaluate the code it encompasses may not be entirely clear. Should db.getDatabase() and fetchAppts() be run as stubs inside the unit test function? The current unit test implementati ...

Verify a roster within a display by utilizing annotations

My solution involves using a listbox to display a list as shown below, and I am also utilizing Chosen.js to allow for selecting multiple records. @Html.ListBox("AllLanguages", new SelectList(ViewBag.Languages, "Id", "Language1")) <div id="languagesDi ...

Generate a new entry by analyzing components from a separate array in a single line

I have a list of essential items and I aim to generate a record based on the elements within that list. Each item in the required list will correspond to an empty array in the exist record. Essentially, I am looking to condense the following code into one ...

Verify that the images have been successfully loaded

I'm in the process of loading 8 images that all share a common class name. For example: <img class="commonClass" src="..." alt="" /> <img class="commonClass" src="..." alt="" /> <img class="commonClass" src="..." alt="" /> How can ...

Mocha test failing to trigger function execution

I've been developing an Express.js application that includes a feature for creating appointments with a post request. This feature involves retrieving and saving data from a third-party API, followed by sending updated API data in the subsequent reque ...

Filter information by the K column within Google Script Editor on Google Sheets

For this particular case, I have data coming from a Google Sheet (4Cat) that is being transferred to another sheet (ImportFeeder) where my Google Script is executed. After executing the script provided below, I am looking to implement a filter script at t ...

How can I make a CSS transition activate only on width increases, not decreases?

My element's width changes under different conditions, and I've implemented CSS with a transition for the width: .element-class { transition: width 500ms ease 0ms; } However, I only want the transition to occur when the width is decreasing. ...

Link the parameters of two polymer elements within a repeat template

In this scenario, my goal is to securely bind attr and attr1. These two variables should be independent from the variable data, unlike other attributes in use. I want each iteration to have its own set of bound components, rather than sharing one data obje ...

How to apply CSS classes to dynamically injected HTML in Angular 7

One of the challenges I'm currently facing is how to assign a CSS class based on a calculation in my component. Here's a snippet from my component class: @Component({ selector: 'app-render-json', template: `<div [innerHtml ...

Rearrange HTML list items automatically according to changes in numeric sort order

I am working on a web page that features a dynamic ranked list. The items in the list are assigned a specific rank order number which changes based on user interactions elsewhere on the page. I have been exploring different options to automatically reorgan ...

How can I ensure that my jQuery code only executes after the mobile CSS has been loaded

When it comes to loading my mobile-only CSS, I typically use a media query similar to: <link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="/includes/css/mobile.css" /> However, in addition to these CSS mod ...

IconButton function in ReactJS malfunctioning specifically in Firefox browser

There seems to be an issue with the click function of IconButton from Material UI not working in any version of FireFox. Below is the code snippet in question: <div className='floating-button visible-xs'> <IconButton touch={true} tool ...