Double your audio experience with Webaudio by playing the sound twice

While working on WebAudio experimentation, I encountered an issue with loading a sound using the JavaScript code below.

function playAudio(){
    var audio = document.getElementById('music');
    var audioContext = new webkitAudioContext();
    var analyser = audioContext.createAnalyser();
    var source = audioContext.createMediaElementSource(audio);
    source.connect(analyser);
    analyser.connect(audioContext.destination);
    audio.play();
}

In addition to playing the sound, I want to visualize it using canvas by utilizing the analyser. The function works correctly the first time it is used, but upon executing it a second time, an error occurs.

> playAudio(); // successfully plays sound
> playAudio(); // error 
InvalidStateError: Failed to execute 'createMediaElementSource' on 'AudioContext': invalid HTMLMediaElement.

The identified cause of this error lies within this specific line of code:

var source = audioContext.createMediaElementSource(audio);

Even though I am creating a new audio context, attempting to reuse the same audio element in the HTML leads to this error.

Answer №1

Utilizing a dynamic approach for creating the audio element (as demonstrated in this fiddle, http://jsfiddle.net/ikerr/WcXHK/), I successfully achieved the ability to play the song in a repetitive manner.

function createAudioElement(urls) {
    var audioElement = document.createElement("audio");

    audioElement.autoplay = true;
    audioElement.loop = false;

    for (var i = 0; i < urls.length; ++i) {
        var typeStr = "audio/" + urls[i].split(".").pop();

        if (audioElement.canPlayType === undefined ||
            audioElement.canPlayType(typeStr).replace(/no/, "")) {
            var sourceElement = document.createElement("source");
            sourceElement.type = typeStr;
            sourceElement.src = urls[i];
            audioElement.appendChild(sourceElement);
            console.log("Using audio asset: " + urls[i]);
        }
    }

    return audioElement;
}

var audioContext = new webkitAudioContext();

function playAudio(){

    var audio = createAudioElement(['http://www.soundjay.com/button/button-1.mp3' ]);      

    if(audio){
        var source = audioContext.createMediaElementSource(audio);
        var analyser = audioContext.createAnalyser();
        source.connect(analyser);
        analyser.connect(audioContext.destination);
        audio.play();
    }
}

playAudio(); // works fine, i can hear a sound
playAudio();
//setTimeout(playAudio,2000);

Demo : http://jsfiddle.net/raathigesh/fueg3mk7/10/

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

Bring in a 3-dimensional model using JSONLoader in three.js

I'm facing some challenges with incorporating a simple 3D object created in Maya into my Three.js project using JSONLoader. The object consists of various materials (Lambert and Phong) and different colors. I used Maya to create a .obj file, then Ble ...

When attempting to display a sub view in Express, a 404 error is encountered

I am currently working with express and jade to display a web page. My intention is to render the page using this format 'http://127.0.0.1:5000/services/landfreight' but I keep encountering a 404 error. router.get('/service/landfreight' ...

What sets cross-fetch apart from isomorphic-fetch?

According to the Redux documentation, cross-fetch is the preferred choice, whereas most other sources recommend using isomorphic-fetch. What sets these two apart? ...

I'm interested in clicking on an image within a div to trigger a page refresh and then automatically hide the div once the page has refreshed

UPDATE 2 SITUATION To prevent access to quiz content until the page is refreshed, I am employing a semi-transparent image with a top-margin off-set. The following code functions flawlessly on one specific page and only once: JavaScript window.addEventL ...

Numerous SVGs sharing identical IDs

Is it possible to include multiple SVGs on an HTML page and utilize the same IDs in each of them? <div> <svg height="0" width="0"> <clipPath id="svgPath"> ........ </svg> <svg height="0" width="0"> < ...

Would you like to learn how to extract data from a specific textbox using jQuery and save it to a variable when the textbox is in

Below is a textbox that I am working on: <input type="text" name="company" id="company" required /> I am trying to figure out how to use jQuery to capture the values inside the textbox whenever they are typed or selected. Despite my efforts, I hav ...

I'm having trouble with my AJAX Update Panel. Can someone please help me figure out what I'm doing wrong?

--------------Handling Gridviews DataBound Event ----------------- protected void grdShowCallingList_DataBound(object sender, EventArgs e) { if (grdShowCallingList.Rows.Count > 0) { foreach (GridViewRow row in grdShowCallingList.Rows) ...

"Bootstrap is functioning properly on my local environment, but it seems to

Utilizing the MVC framework and bootstrap has been successful for optimizing my website locally. However, when I upload it to the server, none of the CSS is being rendered. Additionally, the front page, meant to be a carousel slider, appears as a vertical ...

Text input setting for jQuery UI Slider

Currently, I am utilizing jQuery UI sliders to input values in text boxes. However, I would like this functionality to be bidirectional; meaning if a value is entered into the text box, I want the slider to move to the corresponding position. I am unsure ...

The step-by-step guide to testing an Angular promise using Jasmine

An issue arises when attempting to test the code below using Jasmine, as the console.log in `then` is never called. The question remains: is this problem related to Angular or Jasmine? describe("angular test", function() { var $q; ...

CSS file not loading in an ExpressJS application

I'm facing an issue with my ExpressJS web app where only the HTML files are loading but the CSS rules are not being applied. I have linked the HTML file with the CSS file and also included express.static(path.join(__dirname, 'css')) in my ap ...

Expo: A guide on integrating expo code into an existing Android project

I'm looking to enhance my Android app (which is built in standard Java) by allowing users to create their own 3D models. To achieve this, I want to incorporate a 3D viewer within the app so that users can view and interact with their creations. My pl ...

Obtaining JSON information within the AngularJS Scope

I am delving into the world of AngularJS for the first time and trying to understand it by following this example: http://jsfiddle.net/SAWsA/11/ After successfully acquiring data in JSON format, I encountered no issues. Here is a snippet of the JSON data: ...

Loading a Vuetify component dynamically within a Vue 3 environment

In my Vue 3 project, I am attempting to dynamically load Vuetify components using the code below: <template> <v-chip>try</v-chip> <component :is="object.tag">{{ object.content }}</component> </template> & ...

Enable the ability to upload multiple images on a single page using droparea.js

I am currently utilizing droparea js for uploading images. However, I have encountered an issue where if I try to upload an image in one of the upload menus, it ends up changing all four upload menus simultaneously. <div class="col-md-12"> ...

Ways to identify when a person has scrolled a specific distance

Is it possible to modify the appearance of my top navigation bar once the page has been scrolled a specific number of pixels? I assume this requires some sort of listener to track the amount of scrolling. I came across element.scrollTop, but it doesn' ...

React-scripts testing now displays error messages without a traceback

After recreating the browser version of the TacticToy game using React, I encountered an issue while writing unit tests. The problem is that there is no complete traceback provided for a custom exception, with only the test function being highlighted: htt ...

Having trouble with enter key input not triggering?

I have scoured various resources for answers to my query, including Stackoverflow. Unfortunately, none of the posts I came across have helped me resolve my issue with getting the enter key to work in my project for FreeCodeCamp on Codepen. When I press the ...

Exploring the World of Vue.js Object Imports

I am currently encountering an issue involving the importing of Objects from App.vue into a component. To provide context, this project consists of a Navigation Drawer component and an App.vue file. The Navigation Drawer contains Vue props that can be dyna ...

Error: Chrome is reporting an "Unexpected token :" while Firefox is showing a "SyntaxError: missing ; before statement" issue

Here's the code snippet in question: function getCategoryResponse() { var appid = "1"; $.ajax({ type: 'GET', url: 'http://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/genres?id=36&callback=myCallbackFu ...