Switching the audio file upon button click

I've been attempting to switch the audio file when a button is clicked but I keep encountering this error

Uncaught TypeError: audio.load is not a function

Below is my code, where the goal is to change the audio file upon pressing the button.

If I remove the audio.load() line, the code runs and the src updates, however, the audio itself does not change. What am I overlooking?

HTML:

<!DOCTYPE HTML>
<html>
<body>
  <br>
  <audio controls id="audio">
    <source src = "audio_file_1.mp3"
      type="audio/mpeg">
    Your browser does not support the audio element!
  </audio>
  <br>
  <button onClick="changeAudio();">Change</button>
</body>
<script src="temp.js"></script>
</html>

Javascript:

// temp js
var a = 1;
function changeAudio() {
  var audio = document.getElementById('audio');
  if (a==1) {
    audio.src = 'audio_file_1.mp3';
    a = 2;
  }
  else {
    audio.src = 'audio_file_2.mp3';
    a = 1;
  }
  audio.load();
}

changeAudio();

(Also, for those looking for sample sound files to use in place of audio_file_1.mp3 and audio_file_2.mp3, feel free to suggest them so that others can easily test the code)


Edit Regarding Rob M's Answer:

For individuals facing the same issue, the solution involves modifying two lines:

Firstly, in the HTML code, change <audio control> to

<audio control id="audio_id">

Secondly, in the javascript code, replace audio.load() with

document.getElementById('audio_id').load();

Answer №1

The load() function is not applicable to the <source> element; rather, it should be called on the parent <audio> tag for it to function properly.

Answer №2

It seems like you are attempting to access the <audio> element using its id attribute, but it appears that the id attribute has not been set for the audio tag. To properly define it, it should look something like this:

<audio id="audio" controls>
    <source src = "audio_file_1.mp3"
      id="track" type="audio/mpeg">
      Your browser does not support the audio element!
</audio>

To change the audio file dynamically, you can follow this code snippet:

var a = 1;
function changeAudio() {
  var audio = document.getElementById('audio');
  if (a == 1) {
    document.getElementById('track').src = 'audio_file_1.mp3';
    a = 2;
  } else {
    document.getElementById('track').src = 'audio_file_2.mp3';
    a = 1;
  }
  audio.load();
}

changeAudio();

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

Unable to include a JavaScript file within another JavaScript file

Currently, I am working on a project where I am utilizing Django for the backend and HTML/CSS/JS for the frontend development. On a specific HTML page, I am including two JS files: dom_creator.js and console_page.js. My goal is to access the functionaliti ...

Creating a secure ZIP file with password protection using node.js

Currently, I am faced with the challenge of creating a ZIP file in node.js with password protection. Despite using the "node-zip" module for this task, it lacks the functionality to provide password protection: var zip = new require('node-zip') ...

What is the best way to pass my session token information between various JavaScript files on the server?

Here's the current status of my session tokens on the server: In my server.js file: app.use( session({ secret: "{ ...

Having trouble retrieving the $_SESSION variable accurately from AngularJS

I am working with angularjs and need to retrieve a php session variable. I have created a php file named session.php with the following content: $_SESSION['phone'] = '55551864'; return json_encode($_SESSION['phone']); In my ...

What advantages does using immutablejs offer compared to using object.freeze?

I've scoured the internet trying to find convincing reasons for using immutablejs instead of Object.freeze(), but I still haven't found a satisfactory answer! What are the advantages of working with non-native data structures in this library ove ...

The d3.select function is failing to update the chart on the website

I am facing a challenge in updating data in a d3 chart with the click on an HTML object #id. After successfully coding it in jsfiddle, I encountered issues when implementing it on a web page. The scenario involves a simple leaflet map where the chart is d ...

Adjust the initial slider according to the values displayed in the following four sliders

Having an issue updating the slider value in the first one based on selected values from four other sliders. The selected value should not exceed 50, which is the maximum value in the first slider. Link to Working Fiddle : Below is the HTML code : & ...

Using npm to install packages with multiple package.json files

My current project includes a submodule with another submodule, each having their own package.json file. This is how I set up my project: |root ----|node_modules ----|package.json ----|someFolder ----|submodule_1 -------- |package.json -------- |someFold ...

The absence of the 'subscribe' property on the 'void' type in Angular 2 with asp.net core is causing an issue

Whenever I attempt to use the subscribe function, an error pops up. I faced a similar issue with .map, but it was resolved by replacing the file found at https://raw.githubusercontent.com/Microsoft/TypeScript/Fix8518/lib/typescriptServices.js I have recen ...

AngularJS - Leveraging the power of two-way data binding with JSON strings

I am a beginner with AngularJS and I'm currently working on retrieving, parsing, and displaying data from a SOAP web service. So far, I have been able to successfully make calls to a public weather service, capture and display the XML data that is ret ...

What is the best way to incorporate Vue.js component dependencies into a multi-page application (MPA

When working with a multiple page app, incorporating a component inside another component can be challenging, especially without using a build system. $ npm install sagalbot/vue-select <template> <div id="myApp"> <v-select :value.sy ...

Troubleshooting React and NodeJs Fetch Problem

I am currently working on retrieving data from my API, which is functioning properly. The API endpoint I am trying to fetch results from is http://localhost:5000/api/continents. {"data":[{"continentId":3,"CName":"Atlantis"},{"continentId":2,"CName":"Devia ...

What is the recommended lifecycle hook in Vue.js2 to execute a function when the page is loaded?

I have a dynamic table that can be filled with various numbers of rows, and I want to add an overlay before the data is loaded using my applyOverlay() function. Below is the structure of my HTML: <table id="table" class="datatable" s ...

SyntaxError: An invalid character was encountered (at file env.js, line 1, column 1)

This marks my debut question so kindly indulge me for a moment. I recently stumbled upon a guide that outlines how to dynamically alter environment variables in a React project without the need for re-building. You can find the guide here. The method work ...

When modifying the state of an array within a component, certain values may be overwritten and lost in the process

Currently, I'm faced with the challenge of ensuring that a component displays a loading screen until all images have completed loading. This is necessary because there are approximately 25 images that must finish loading before the page can be display ...

The script tags encountered an issue loading the resource with a status code of 404

Currently working on an ASP.NET MVC project and encountered an issue on one of the pages. Here is the code snippet with a script included at the bottom... @model IEnumerable<PixelBox.Dtos.ItemGetDto> @{ ViewBag.Title = "Index"; } <body> ...

Nodejs application encountering a problem with the findUser method in Active Directory

I have encountered an issue while using the activedirectory npm package with Nodejs v16.18.1. The code snippet below is used for authentication and finding user details: Could someone please assist with this? async authUserActiveDirectory(usernameAD: stri ...

"Enhance Your Highchart Experience by Adding Hyperlinks to Every Segment of Your Stacked Bar

I am seeking to assign a specific link to each segment of a stacked 100% bar chart. Check out this demo of a stacked bar chart: http://www.highcharts.com/demo/bar-stacked Here's what I am trying to accomplish: Please visit , input data in the left t ...

I rely on Grunt to manage my Angular 1 app, along with grunt-connect to host the website. However, when I refresh the page, there is no fallback mechanism in place, resulting in a 404 error and

Currently, I am utilizing Grunt to manage my angular 1 application and grunt-connect to serve the website. However, I have encountered an issue where on refresh, there is no fallback mechanism in place which results in a 404 error and a blank white screen. ...

Tips for maintaining the active state of an item within a component that loops through a dataset

I am working with an array of objects (specifically, posts represented as strings) and I am looking to be able to edit each one individually. However, I am encountering an issue where clicking on the edit button triggers editing for all posts at once: co ...