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

Add a border to the 'contenteditable' class in a Bootstrap table after it has been modified

Looking for help with JavaScript and jQuery! I have a script that creates an HTML table from a CSV file, using Bootstrap for styling. I want to add CSS or a border to a table cell after it has been edited, but my jQuery attempts haven't worked. Any su ...

Steps for loading a different local JavaScript file by clicking on a button

My goal is to reload the browser page and display a different ReactJS component/file when a button is pressed. Initially, I attempted using href="./code.js" or window.location="./code.js" within the button props, but unfortunately, it did not yield the des ...

I possess information stored within the array object below, and I aim to transform it into a different array object format

Here is the response I received from my API: let data = [ { date: '2021-04-27', formatted_date: 'Apr 27', location: [ { date: '2021-04-27', formatted_date: 'Apr 27', countr ...

"Implement image uploading and retrieval functionality in your application by utilizing Parse and Back4App with the help of Node

It seems like I have a question that may have already been answered, but I can't find the right solution for my issue. I'm facing trouble with my code and can't figure out what's wrong. The problem arises when I try to upload specific ...

What is the process for retrieving the AJAX response text?

When it comes to my AJAX development, I rely on prototype and utilize the following code: somefunction: function(){ var result = ""; myAjax = new Ajax.Request(postUrl, { method: 'post', postBody: postData, content ...

The JavaScript code is not executing properly within the HTML document

I am trying to execute a function from my JavaScript file in my HTML page. Here is the code snippet: index.html <!DOCTYPE html> <html><body> <h2>Web1</h2> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jq ...

In an Electron-React-Typescript-Webpack application, it is important to note that the target is not a DOM

Rendering seems to be working fine for the mainWindow. webpack.config.js : var renderer_config = { mode: isEnvProduction ? 'production' : 'development', entry: { app: './src/app/index.tsx', //app_A: './src/a ...

What are the various undisclosed schema types in A-Frame?

I've been exploring different examples of property types in the official documentation and various Github repositories (though now I can't remember which ones). The latter introduced me to unique properties like "min" and "max" for numbers, as we ...

Issue with Repeated String Test in JavaScript: Single Failure Detected

Currently tackling the Repeated String Challenge on HackerRank. The challenge description goes as follows: A string, denoted by s, consisting of lowercase English letters is repeated infinitely. With an integer, n, the goal is to determine and output the ...

Difficulties with validating phone numbers

I'm having an issue with my JavaScript code that is supposed to validate a phone number field, but it doesn't seem to be working. Even if I enter incorrect values, the form still submits. Here's the snippet of my code: <script> functi ...

Ways to reduce the amount of time spent watching anime when it is not in view

My anime experiences glitches as the black container crosses the red, causing a decrease in duration. Is there a way to fix this glitch? I attempted to delay the changes until the red path is completed, but the glitches persist. delayInAnimeSub = ourVilla ...

Decoding JavaScript content with Python

Currently, I am dissecting this specific portion of HTML <script type="text/javascript"> var spConfig = new Product.Config({"attributes":{"150":{"id":"150","code":"size_shoe","label":"Schuhgr\u00f6\u00dfe","options":[{"id":"494","label ...

Is there a way to automate the loading process when a file is uploaded to an HTML input field?

How can I upload a file via Ajax post in HTML without clicking the button? Currently, my code only works after clicking the bootstrap button. My current implementation is as follows: $(document).ready(function () { $("#but_upload").click(function () { ...

Escaping back slashes in Node.js

I am currently encountering an issue with escaping backslashes. Below is the code snippet that I have attempted. The problem lies in how to assign a variable containing an escaped slash to another variable. var s = 'domain\\username'; ...

The jQuery script operates just one time

Recently, I encountered a small issue with my script. It only seems to work once - after that, I have to refresh the page in order to remove a favorite article (which the script is supposed to do). $("a.fav_no").on('click', function () { ...

Using Node.js to create a RESTful API that pulls information from MongoDB

I am currently working on creating a REST API using Node.js to retrieve the last N rows from a MongoDB collection. Here is my current code snippet: var express = require("express"); var app = express(); var bodyParser = require("body-pa ...

What is the reason for all the buttons activating the same component instead of triggering separate components for each button?

I am facing an issue with my parent component that has 3 buttons and 3 children components. Each button is supposed to open a specific child component, but currently all the buttons are opening the same child component when clicked. The children components ...

Guide on adding a new member to Mailchimp through node.js and express

Hello, I've been delving into working with APIs, particularly the mail-chimp API. However, I've encountered a problem that has me stuck: const express=require("express"); const bodyparser=require("body-parser"); const request=require("request" ...

A comprehensive guide on creating a package that combines an href link with an <li> element

I am currently using the <li> tag to display href links. The issue I am facing is that when I click on the 'box,' it does not directly link to another page. Instead, I have to click on the href link for it to redirect to another page. Is th ...

How to show the current week using React Native

Looking to show the current week of the month in a specific format using react-native: (Week 2: 05.10 - 11.10) (for example, displaying week 2 of the current month) Any ideas on how to make this happen? I'm aware of packages like momentjs that can ...