utilizing JavaScript to play an audio file in .mp3 format on my timer

Hi everyone, I'm a complete beginner in JavaScript. Recently, I've been working on coding a timer that resets its countdown whenever there is mouse movement or a key on the keyboard is pressed. I've managed to get the timer functionality working, but I'm struggling to figure out how to play the audio from my alarm.mp3 file.

I know it's a simple issue, but after spending almost a month trying to solve it, I'm starting to feel burnt out. Below is my JavaScript code, and any help or guidance would be greatly appreciated.

const fiveMinutes = 5
var start, diff, minutes,seconds;

var display;
var timerStarted = false
var resetCtr = 0;  
var debugMsg;
const debug = true;


function startTimer(duration) {
    
    start = Date.now()

    function timer() {
        diff = duration - (((Date.now() - start) / 1000) | 0);

        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        
        display.textContent = minutes + ":" + seconds;
};
    timer();
    setInterval(timer, 1000);
}

function btnStartTimer() {
    if (!timerStarted) {
        timerStarted = true;
        startTimer(fiveMinutes);
    }
}

function resetTimer(){
    if (timerStarted) {
        startTimer(fiveMinutes);
    }
}


window.onload = function () {
    display = document.querySelector('#time');
}

Just to give you a bit of context, I'm using Visual Studio Code on Windows 11 for this project.

Answer №1

// To generate a sound source, use the code snippet below:

const audio = new Audio("/path/to/your/song.mp3");

// When you wish to play the sound, simply invoke the following function:

audio.play();

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

Are you interested in implementing the switcher function in a React JS class component?

I am having trouble implementing the switcher method in my react app, which is built using class components. Can you provide guidance on how to utilize the useThemeSwitcher() function in class components? How can I integrate this function into my web app ...

The cookie's expiration time is being set to 1 hour, rather than the specified maxAge duration

My file contains a cookie that consistently sets to 1 hour as the default, even when I specify a maxAge of 12 seconds. res.cookie("my-cookies", req.body.id_token, {maxAge: 12000, httpOnly: false}); ...

Using jQuery to drag a div and drop it to swap out an image in a different

I am looking to implement a drag and drop function where I can move elements from one div to another, each containing different images. However, I want the image displayed in the second div to change based on the element being dragged. For example: When d ...

Toggle the on and off functionality of a button using ajax response for content display

I'm struggling to figure out why the button isn't working for me. I am familiar with how to enable and disable buttons using attr and prop. $(document).on("click", "#btn", function(){ $(this).html("Sending..."); $(this).prop("disabl ...

What is the best way to implement rate limiting for asynchronous API calls within a specific timeframe?

I have a project that requires me to make over 500 calls simultaneously from my NodeJS server to a third-party server. The issue is that the third-party server has a restriction of only allowing a maximum of 50 calls per second. Can someone assist me in im ...

Enhance the functionality of AngularJS (Restangular) by encapsulating service methods with a

Initially, when using basic $http, I had this code snippet in a service: var fetchSomeData = function() { var deferred = $q.defer(); $timeout(function() { $http.get('...mylongurl', { headers: { 'Content-Type& ...

The presence of a Bootstrap addon is resulting in horizontal scrolling on mobile devices within the webpage

I am encountering a peculiar issue with an input-group in my cshtml file which features a Bootstrap addon. The problem arises on mobile devices, where upon focusing on the input field, the page scrolls horizontally to the right, revealing the right margin ...

Reset the AJAX object using jQuery

Currently, my code looks like this: object1 = $.ajax({ .. .. }); If an error occurs, I would like to have the ability to restart the ajax request. For instance, if the user's connection is lost, I want to be able to easily call the same ajax again w ...

Transforming Unicode escape sequences into symbols and displaying them in a DOM element

Using the latest versions of Firefox and Chrome with jQuery 1.x edge. When an ajax request returns a single line of minified JSON text like this: { "fromSymbol": "\\u04b0", "toCurrency": "AUD", "toSymbol": "\\u0024", "convFact ...

ASP updatePanels causing scrollable grid plugin offsetWidth to be undefined

I am attempting to create scrollable gridviews within update panels by utilizing a function that is called in the pageLoad() function LoadScrollPopupOverridesBehavior() { $('.GridViewPopupWithOverride').Scrollable({ ScrollHeight: 350 ...

Having issues with my custom AngularJS directive functionality

app.directive("myData", function() { return { templateUrl: '/my-data.html' }; }); my-data.html file code <tr ng-repeat="employee in employees"> <td>{{employee.id}}</td> <td>{{employee.name}}</t ...

Gradually appear/disappear div element with a delay added

Storing divs in an array and deleting them after appending is my current method. Now, I'm looking to incorporate a fade-in and fade-out effect on each div with a delay. Check out this code snippet : var arr = $(".notification"); function display ...

What is preventing me from using Selenium/Javascript to control Firefox on Ubuntu 22.04, when I am able to do so with Python?

My python script effectively controls Firefox using Selenium: from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Firefox() driver.get("https://dev.to") driver.find_element(By.CLASS_NAME, "crayons ...

Encountering a problem with populating data in postgresql

After executing the npm run seed command to populate data into PostgreSQL, even though the seeding process seemed to be successful, I couldn't locate the seeded data in the PostgreSQL database. Can anyone advise on what might have gone wrong or sugges ...

What is the best way to implement a link instead of a string within a custom JavaScript function?

I am looking for a way to replace parameters in a string with the values provided using a helper function - type FormatStringParameter = string | number; /** * Helper function to substitute parameters in a string with the specified values * * @param in ...

JavaScript doesn't seem to be functioning properly within PHP

I have implemented the supersized jQuery script to incorporate sliding backgrounds on my WordPress page. Now, I aim to create unique slides for different sites and require a PHP if request. This is my code: <?php if ( is_page(array('Restaurant&a ...

The Express Generator is having trouble detecting the routes within the users file when using app.use('/login', users)

Having used the express generator, I am facing confusion regarding why I cannot utilize the users.js routes file for my login routes. I have created the POST route below, and when I keep it in app.js, everything works smoothly. However, if I attempt to mo ...

Sequelizejs establishes a belongsToMany relation with a specified otherKey

I am currently developing an app centered around songs and artists, and here is the database schema I have designed: Each Song can have multiple Artists associated with it, and each Artist can be linked to several Songs as well. This establishes a many-to ...

Getting the value of an element using a string in JQuery

How can I achieve the following using JQuery? var test = "'#ISP'"; alert($(test).val()); I am receiving a "Syntax error, unrecognized expression." I believe I might be overlooking something here. Thank you in advance! ...

Plot the components of an array and calculate the instances that JavaScript executes

I have an array containing information about PDF files stored in a buffer. Let's imagine this array holds ten PDF files structured like this: [{ correlative: "G-22-1-06", content: <Buffer 25 50 44 46 2d 31 2e 34 0a 25 d3 eb e9 e1 0a ...