Attempting to modify the audio tag's src attribute with JavaScript

I've been doing online research for the past few weeks and have come across similar solutions to what I'm trying to achieve. However, due to my limited knowledge of javascript, I am struggling to implement them effectively.

My goal is to have an audio tag that plays a different audio file depending on the day of the month. Essentially, when clicking play, the corresponding file for that specific day should be played using the audio player.

Below is my current audio tag:

<audio preload="metadata" controls="controls" src="" id="todays" autoplay="none"></audio>

This is the JavaScript code I'm using:

function todaywm() {
    var a, dayofmonth
    a = new Date()
    dayofmonth = a.getDate()
    document.getElementById('todays').src = radiolinks[dayofmonth]
}
var radiolinks = new Array(31) 
radiolinks[1] = "audio/day01.mp3"
radiolinks[2] = "audio/day02.mp3"
radiolinks[3] = "audio/day03.mp3"
// etc...
radiolinks[29] = "audio/day29.mp3"
radiolinks[30] = "audio/day30.mp3"
radiolinks[31] = "audio/day31.mp3"

Despite my efforts, I have not been successful in making it work as intended. I'm still relatively new to javascript and learning as I go.

Answer №1

New Update: Version 2

The second version of the audio player now supports a properly formatted Array Literal and plays the corresponding position based on the day of the month. Additionally, there is a form included that allows you to input data and generate an array literal.

Try out the dailyAudio Player here

Generate Playlist Array here


If you already have all 31 files, there is no need to use an array. You can manipulate the 2 digits in your file paths for easier access. Ensure that both your webpage and mp3 files are in the correct folder on your server.

For example:

  • Webpage location:

    http://www.domain.com/path/to/index.html

  • Song for day 28 location:

    http://www.domain.com/path/to/audio/day28.mp3

  • Song for day 1 location:

    http://www.domain.com/path/to/audio/day01.mp3

Check out a working demo here: Demo Link

To test it:

  1. Fork the project.
  2. Navigate to the file dailySong.js
  3. Comment out line 13 (Place "//" at the beginning of line 13)
  4. Uncomment line 17 (Remove "//" from the beginning of line 17)
  5. Line 17 plays music only on days 18, 19, & 20 of the month.

Note: The code snippet below won't work due to strict sandboxing. Visit this link for testing instructions.

function nowPlaying() {
  var player = document.getElementById('dailySong');
  var obj, dayOfMonth, X;
  obj = new Date();
  dayOfMonth = obj.getDate();
  X = pad(dayOfMonth, 2); //:::::............. This is to ensure that numbers under 10 get that extra 0 padding.
  player.src = "audio/day" + X + ".mp3"; //:::::........This concats X to a string that will be assigned to src
  player.load(); //:::::.................When changing src, you must .load() the player before you can play.
}

// This utility function is to pad numbers less than 10
// https://stackoverflow.com/a/30387967/2813224
function pad(num, len) {
  return '0'.repeat(len - num.toString().length) + num;
}

//Start playing when the page has loaded completely.
window.onload = nowPlaying;
h1 {
  font-size: 2rem;
  color: red;
}
<audio preload="metadata" controls="controls" src="" id="dailySong" autoplay="none"></audio>
<h1>The demo may not work due to stringent sandbox rules in snippets. Follow the testing instructions provided at: <br/><a href="http://plnkr.co/edit/vzvOD0XIi61qfVAASWub?p=preview" target="_blank">http://plnkr.co/edit/vzvOD0XIi61qfVAASWub?p=preview</a></h1>

Answer №2

Have you remembered to add a semicolon at the end of each line?

Answer №3

While it's not mandatory to include a semicolon at the end of each statement, I highly recommend it as good practice! Additionally, if you're encountering issues with the script, please check if the mp3 files are located in a folder named "audio" relative to where the script is placed.

Answer №4

Hey @zer00ne, check out the code I wrote for my custom audio player using the Foundation Framework:

<div id="customModal" class="reveal-modal tiny" data-reveal aria-labelledby="custom-broadcast" aria-hidden="true" role="dialog">
    <script type="text/javascript" src="js/custom.js"></script>
    <h3 id="custom-broadcast" class="text-center">Custom Broadcast</h3>
    <div class="audio-player"><audio preload="auto" controls="controls" id="custom" src=""></audio></div>
    <a class="close-reveal-modal" aria-label="Close">&#215;</a>
</div>

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

"Transferring a JavaScript variable to Twig: A step-by-step guide for this specific scenario

When it comes to loading a CSS file based on the user's selected theme, I encountered an issue while trying to implement this in my Symfony application using Twig templates. The code worked flawlessly on a simple HTML page, but transferring it to a Tw ...

Encountering an error when trying to destructure a property of null

The concept of destructuring is fascinating, but I have been facing some challenges when trying to destructure nested objects. Consider the following code snippet: const { credit: { amount }, } = userProfile This can be risky because if the &ap ...

How can we use Cypress to check if we are at the final slide in the presentation?

I am facing a challenge with multiple slideshow files that contain varying numbers of slides. Some have 10 slides, while others have 80 slides. My goal is to test every slide by using the forward and backward arrow buttons for navigation. Currently, I am c ...

Angular Leaflet area selection feature

Having an issue with the leaflet-area-select plugin in my Angular9 project. Whenever I try to call this.map.selectArea, VSCode gives me an error saying that property 'selectArea' does not exist on type 'Map'. How can I resolve this? I& ...

Sending both the minimum and maximum slider values to PHP using POST can be achieved by formatting the data correctly

I am attempting to transmit the minimum and maximum values to PHP using submit through a dual slider bar The static page makes a request to the server-side PHP code <?php include('server/server.php') ?> Below is the JavaScript code ...

Create an Android application using Node.js

While developing my mobile application, I am utilizing html5 with node.js to create a chat box for users connected on the same wireless network. However, I encounter an issue when coding on my desktop using node.js software. How can I overcome this challen ...

Transform Promise-based code to use async/await

I'm attempting to rephrase this code using the async \ await syntax: public loadData(id: string): void { this.loadDataAsync() .then((data: any): void => { // Perform actions with data }) .catch((ex): v ...

Unable to retrieve information from the JSON object

Here's the script I'm working with: <script type="text/javascript> function getData(username){ $.ajax({ url: '{% url "data" %}', data: { ' ...

Is there a way to make res.render in node.js/express/mongo wait until the database search is finished before loading?

Having some difficulty with loading a table properly on my page because the information is not being passed to the ejs template before the page loads. I'm fairly new at this and could use some assistance! Just a heads up, owneditems consists of an ar ...

How to pass data/props to a dynamic page in NextJS?

Currently, I am facing a challenge in my NextJS project where I am struggling to pass data into dynamically generated pages. In this application, I fetch data from an Amazon S3 bucket and then map it. The fetching process works flawlessly, generating a se ...

A function injected into a constructor of a class causes an undefined error

As I delve into learning about utilizing typescript for constructing API's, I have encountered a couple of challenges at the moment. Initially, I have developed a fairly straightforward PostController Class that has the ability to accept a use-case wh ...

What could be causing the template UI to not display the Vue data?

As someone new to Vue, I have defined my Vue code in the following way: import Vue from "vue"; export default Vue.extend({ data: () => { message: "show message"; }, }); <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js ...

The JavaScript setTimeout function not triggering repetitively for 10 instances

I'm facing an issue with a JavaScript/jQuery function that is designed to call itself multiple times if there is no available data. This is determined by making a web service call. However, the logging inside the web service indicates that it is only ...

Transform a group of objects in Typescript into a new object with a modified structure

Struggling to figure out how to modify the return value of reduce without resorting to clunky type assertions. Take this snippet for example: const list: Array<Record<string, string | number>> = [ { resourceName: "a", usage: ...

Is it feasible for a form button to perform multiple actions simultaneously?

I am interested in exploring the possibility of having a submit form button perform multiple actions. Currently, I have a custom form that is sent to a Google Spreadsheet using AJAX and I am also utilizing the Blueimp Jquery File Upload plugin. My goal is ...

Learn how to use jQuery to load a text file containing arrays and then format them as

I'm attempting to load a .txt file containing multidimensional arrays using AJAX, and then sort through the data to display it on my website. However, I'm facing an issue where the data is only returning as plain text, even after trying to use JS ...

Is Formik Compatible with TextareaAutosize?

I've implemented react-textarea-autosize and formik in my project, but I'm having trouble connecting the change events of formik to TextareaAutosize. Can anyone guide me on how to do this properly? <Formik initialValues={{ ...

CSS margin-left causing issues in Chrome Extension

My current situation is incredibly puzzling, as I am at a loss for what is happening. I developed a Firefox add-on using jQuery and CSS to revamp a website. When attempting to transfer the add-on to Chrome (which was relatively straightforward due to the s ...

Error: The variable "details.date.getTime" is not defined and cannot be accessed

Currently, I am utilizing https://github.com/zo0r/react-native-push-notification to display notifications. Specifically, I am using scheduled notifications with datetimepicker. Previously, I have successfully used this in another project without any errors ...

Does Next.js pre-render every page, or does it only pre-render the initial page?

As I dive into the world of nextjs, I'm coming across conflicting information. Some sources claim that nextjs only prerenders the first page, while others suggest that all pages are prerendered by default. This contradiction has left me confused about ...