"Enhance User Experience with Autoplay.js for Interactive Content and Sound Effects

I'm trying to get both the animation and audio to start playing automatically when the page loads. Currently, the animation pauses when clicked, but I want it to load along with the audio playback.

I attempted to use var playing=true; to enable autoplay, but it didn't seem to work as expected.

var x = document.getElementById("myAudio");


function playAudio() { 
  x.play(); 
} 

function pauseAudio() { 
  x.pause(); 
} 


//A function to return a random number between a min and a max value
function randomNumber(min, max) {
  number =  Math.floor((Math.random()*(max-min))+ min);
  return number;
}

//Initialise starting values
var purple, blue, cyan, green, yellow, orange, red;
purple = 40;
blue = 35;
cyan = 45;
green = 35;
yellow = 45;
orange = 20;
red = 50;

//To start with the equalizer is paused
var playing=true;

// A Function to change the height of a column more or less randomly
function changeHeight(column, height) {
  height-=randomNumber(-20,20);
  if (height>100) height=100;
  if (height<2) height=2;
  column.style.height=height + "px";  
  return height;
}


//A Function that will be run every 50ms to animate the equalizer
function animate() {
  if (playing) {
    purple = changeHeight(document.getElementById("purple"),purple);     blue = changeHeight(document.getElementById("blue"),blue); 
    cyan = changeHeight(document.getElementById("cyan"),cyan); 
    green = changeHeight(document.getElementById("green"),green); 
    yellow = changeHeight(document.getElementById("yellow"),yellow); 
    orange = changeHeight(document.getElementById("orange"),orange); 
    red = changeHeight(document.getElementById("red"),red); 
    
    //Repeat this function every 50 ms
    setTimeout(animate, 60);
  }
}

//A Function to play or pause the animation
function play() {
  if (playing) {
    playing=false;
    document.getElementById("button").value="Play"; 
    x.pause(); 
  } else {
    playing=true;
    document.getElementById("button").value="Pause";
    x.play(); 
    animate();
  }
}
.equalizer {
  text-align: center;
  margin: 10px auto;
  width: 380px;
}

.column {
  display: inline-block;
  width: 10px;
  margin: 2px;
}

#purple {
  height: 40px;
  background-color: #000000;
}

#blue {
  height: 35px;
  background-color: #000000;
}

#cyan {
  height:45px;
  background-color: #000000;
}

#green {
  height: 35px;
  background-color: #000000;
}

#yellow {
  height: 45px;
  background-color: #000000;
}

#orange {
  height: 20px;
  background-color: #000000;
}

#red {
  height: 50px;
  background-color: #000000;
}

#black {
  display: inline-block;
  height: 120px;
  width: 1px;
  background-color: #ffffff;
    
}
<audio id="myAudio">
  
  <source src="https://neue.run-time.co.za/wp-content/uploads/2020/11/Connected-Original-Mix-Melosense.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

<script>
var x = document.getElementById("myAudio");


function playAudio() { 
  x.play(); 
} 

function pauseAudio() { 
  x.pause(); 
} 
</script>
<div class="equalizer" onclick="JavaScript: play();" value="Play" id="button">
  <span class="column" id="purple"></span>
  <span class="column" id="blue"></span>
  <span class="column" id="cyan"></span>
  <span class="column" id="green"></span>
  <span class="column" id="yellow"></span>
  <span class="column" id="orange"></span>
  <span class="column" id="red"></span>
  <span id="black"></span>
  <br />

Answer №1

The equalizer animation and audio playback are triggered by the user clicking on the equalizer. This functionality is achieved through the execution of the play function. To enable automatic playback upon loading, we must detect the onload event.

Just a few changes are required. Initially, the playing flag should be set to false, and window.onload should be assigned to play. Here is the updated snippet. It is worth noting that certain systems, like Safari on iOS, may require user interaction to initiate sound playback automatically. This code has been tested on Windows 10 with Edge, Firefox, Chrome, and IE11, and it appears to work fine.

var x = document.getElementById("myAudio");


function playAudio() { 
  x.play(); 
} 

function pauseAudio() { 
  x.pause(); 
} 
</script>
<div class="equalizer" onclick="JavaScript: play();" value="Play" id="button">
  <span class="column" id="purple"></span>
  <span class="column" id="blue"></span>
  <span class="column" id="cyan"></span>
  <span class="column" id="green"></span>
  <span class="column" id="yellow"></span>
  <span class="column" id="orange"></span>
  <span class="column" id="red"></span>
  <span id="black"></span>
  <br />
<script>
var x = document.getElementById("myAudio");


function playAudio() { 
  x.play(); 
} 

function pauseAudio() { 
  x.pause(); 
} 


//A function to return a random number between a min and a max value
function randomNumber(min, max) {
  number =  Math.floor((Math.random()*(max-min))+ min);
  return number;
}

//Initialize starting values
var purple, blue, cyan, green, yellow, orange, red;
purple = 40;
blue = 35;
cyan = 45;
green = 35;
yellow = 45;
orange = 20;
red = 50;

//Initially, the equalizer is paused
var playing=false; //WAS true

// A Function to change the height of a column more or less randomly
function changeHeight(column, height) {
  height-=randomNumber(-20,20);
  if (height>100) height=100;
  if (height<2) height=2;
  column.style.height=height + "px";  
  return height;
}


//A Function that will be run every 50ms to animate the equalizer
function animate() {
  if (playing) {
    purple = changeHeight(document.getElementById("purple"),purple);     blue = changeHeight(document.getElementById("blue"),blue); 
    cyan = changeHeight(document.getElementById("cyan"),cyan); 
    green = changeHeight(document.getElementById("green"),green); 
    yellow = changeHeight(document.getElementById("yellow"),yellow); 
    orange = changeHeight(document.getElementById("orange"),orange); 
    red = changeHeight(document.getElementById("red"),red); 
    
    //Repeat this function every 50 ms
    setTimeout(animate, 60);
  }
}

//A Function to play or pause the animation
function play() {
  if (playing) {
    playing=false;
    document.getElementById("button").value="Play"; 
    x.pause(); 
  } else {
    playing=true;
    document.getElementById("button").value="Pause";
    x.play(); 
    animate();
  }
}

window.onload = play;//ADDED
.equalizer {
  text-align: center;
  margin: 10px auto;
  width: 380px;
}

.column {
  display: inline-block;
  width: 10px;
  margin: 2px;
}

#purple {
  height: 40px;
  background-color: #000000;
}

#blue {
  height: 35px;
  background-color: #000000;
}

#cyan {
  height:45px;
  background-color: #000000;
}

#green {
  height: 35px;
  background-color: #000000;
}

#yellow {
  height: 45px;
  background-color: #000000;
}

#orange {
  height: 20px;
  background-color: #000000;
}

#red {
  height: 50px;
  background-color: #000000;
}

#black {
  display: inline-block;
  height: 120px;
  width: 1px;
  background-color: #ffffff;
    
}
<audio id="myAudio">
  
  <source src="https://neue.run-time.co.za/wp-content/uploads/2020/11/Connected-Original-Mix-Melosense.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

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

Exploring the depths of nested object arrays and navigating through historical indexes

I am working with nested object arrays within an array and looking to determine the path of a specific key. For instance: const dataList = [ [ [{id: 100,name: 'Test1'}, {id: 120,'Test12'}], [{id: 101,name: 'Test1&apo ...

jQuery not refreshing properly

I'm currently in the process of creating a script to switch the language on a website using PHP and Ajax/jQuery. I would like the page content to refresh without having to reload the entire page. So far, this is what I have come up with: $( "a[data-r ...

Why do certain list items on my page have a gap between their border and content?

I recently encountered an issue with my list of items and their styling. Each list item contains an anchor element with a gray background, while the item itself has a gradient bottom border. However, I noticed that in some cases, there was a white line ap ...

Can you explain the functionality of the Json onLoad method and how can I use it to send a response?

function MakeJsonRequest() { JsonRequest.setRequestHeader("Content-type", "application/json"); JsonRequest.send(Data); JsonRequest.onload = function() { ProcessJsonResponse(this.responseText); } } // The Som ...

Error encountered: The JSON format provided for Spotify Web-API & Transfer User's Playback is invalid

Utilizing the spotify-web-api-js has been a smooth experience for me when interacting with Spotify Web API. However, whenever I attempt to use the transferMyPlayback() method to switch devices, I consistently run into an error response indicating a malfor ...

What is the best way to handle .jsx files in my library bundling process with Rollup?

Currently, I am in the process of developing a component library using storybook and rollup. Here is the configuration file rollup.config.mjs /* eslint-disable import/no-extraneous-dependencies */ import peerDepsExternal from 'rollup-plugin-peer-deps- ...

Vue: Conditionally importing SCSS when a component is instantiated

My goal is to import Material SCSS exclusively for my Admin component. While this setup works smoothly during local development, the issue arises when I deploy my site to Firebase hosting - the Material styles start affecting not just my Admin component, ...

Enhancing the functionality of localStorage

I am attempting to append a value to a key within the HTML5 localStorage. Take a look at my code below: var splice_string = []; splice_string += "Test value"; var original = JSON.parse(localStorage.getItem('product_1')); origina ...

Building a dynamic 3-tier selection dropdown menu using an Input feature populated with JSON information

My goal is to create a dynamic dropdown selection group, where each selection depends on the previous one. I have tried the code below, and while I can populate the data for the first dropdown, the second and third dropdowns remain empty. I would greatly a ...

What is the best way to configure an EmailId validator in Angular 6 to be case insensitive?

My register and login page include a form validator pattern matching for the registration form. this.registerForm = this.formBuilder.group({ firstName: ['', Validators.required], emailId: ['', [Validators.required, Validators.patt ...

To avoid any sudden movements on the page when adding elements to the DOM using jQuery, is there a way to prevent the page from

I have a challenge where I am moving a DIV from a hidden iFrame to the top of a page using jQuery. Here is my current code: $(document).ready(function($) { $('#precontainer').clone().insertBefore(parent.document.querySelectorAll(".maincontainer" ...

Having trouble storing data in a MYSQL database with NodeJS and ReactJS

When trying to submit the form, a "Query Error" popup appears and data is not being saved in the database. API router.post("/add_customer", (req, res) => { const sql = `INSERT INTO customer (name, mobile, email, address, state, city, policytype, insu ...

Boss declares, "Display the iFrame with no borders visible."

Good day to everyone, I am currently dealing with an issue on the page: It seems to be working perfectly in all of my browsers except for Internet Explorer. Since I don't have IE, I'm having trouble troubleshooting this. My boss mentioned somet ...

The Express.js static() function seems to have trouble serving files from subdirectories that are more than one level deep

My Express.js app has a folder structure displayed on the left. Line 19 utilizes static(). The path for './client' is defined, with path.join() included as well. In the network log on the right, all assets load properly except for the components ...

Exploring the Crossroads of JSP and External Javascript Documents

I am new to using external JavaScript files (*.js). I have my JSP file ready, but my manager wants me to incorporate graphics into it. After searching, I found some *.js files. However, I am unsure of how to connect them with my JSP page. I need a way to ...

a JavaScript method in Selenium for performing a double-click action on a WebElement

Since selenium allows for the execution of JavaScript, I am interested in clicking and double-clicking on a web element or x, y coordinate using JavaScript. I prefer to use JavaScript because the web element in question is a Flash/SVG object on the browser ...

I am trying to figure out how to extract the filename from a form using PHP, but unfortunately, the $_FILES["filename"]["name"] method doesn't appear to be working. Can anyone help me with this issue

Having an issue with a form below that is supposed to extract some details into a mySQL database. Unfortunately, every time I try to retrieve the file in the form, it returns null. Unsure of the reason behind this, so any assistance would be much appreciat ...

What is the best method for compressing and decompressing JSON data using PHP?

Just to clarify, I am not attempting to compress in PHP but rather on the client side, and then decompress in PHP. My goal is to compress a JSON array that includes 5 base64 images and some text before sending it to my PHP API. I have experimented with l ...

Executing system commands using Groovy is a breeze

One of the scripts I have is a sample.js script that allows me to view files located on the server myHost. It works perfectly: var exec = require('ssh-exec') var v_host = 'myHost' exec('ls -lh', { user: 'username&apo ...

Transferring information from a service to an AngularJS controller

I have a service that retrieves data from a URL provided as a parameter, and it is functioning correctly. However, when attempting to pass this data to a controller's $scope in AngularJS, I am not receiving any data. var app = angular.module("Recib ...