Verifying the Legitimacy of a Path in an Audio File

Attempting to play an audio file:

path = '/public/recordings/weekday/1.mp3'
const audio = new Audio(path)
audio.play()

If the path is invalid, a warning message appears in the console:

Uncaught (in promise) DOMException: Failed to load because no supported source was found.

Is there a JavaScript method available to verify if the file exists before attempting to play it?

I believe the solution might be found in this documentation:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType

I did come across a workaround that I am not entirely fond of:

audio.addEventListener('error', function (err) {
   if (err.path[0].error.message.includes('DEMUXER_ERROR_COULD_NOT_OPEN')) {
      this.handleError()
    } else {
      this.handleSomeOtherError()
    }
}.bind(this), false)

Answer №1

Put it into a vow.

function PerformTask() {
path = 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3';
var audio = new Audio(path);
var playPromise = audio.play();
if (playPromise !== undefined) {
  playPromise.then(_ => {
    audio.setAttribute("controls", "controls");
    document.body.appendChild(audio);
    audio.play();
  })
  }
  }
<button onclick="PerformTask()">Give it a shot</button>

Answer №2

Implementing a promise was beneficial:

const startPromise = this.audio.play();
if (startPromise !== undefined) {
    startPromise.then(function() {
      console.log('Playback started automatically!')
    }).catch(function(error) {
       console.log(error)
       this.handleError()
    }.bind(this), false);
 }

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

Is it possible to retrieve the var name from an interpolated expression using template literals?

Suppose I have a variable like this: myVar = `Some text with ${eggs} and ${noodles} or ${pies}`; Is there a method to obtain myVar as an unprocessed string prior to variable substitution, essentially "Some text with ${eggs} and ${noodles} or ${pies}"? M ...

When attempting to view the PDF file, it appears completely void

After spending countless hours on this task, I'm still not making any progress. My goal is to download a PDF file from my server while currently running the operation on localhost. However, whenever I open the downloaded PDF, all I see is a blank whit ...

"Selecting an element through Drag/Drop will result in the element being

INQUIRY I've encountered an issue with a draggable element ($("#draggable")) that interacts with a checkbox ($('#checkable')). When the $('#draggable') is dragged onto a box ($('#droppable')), it checks $(&apos ...

What is the best way to transfer attributes from a sub-menu item to its parent in the hierarchy?

Recently, my employer made the decision to expand the menu bar by adding additional sub-pages. However, what used to work perfectly fine with just one sub-menu is now encountering issues due to the new sub-menu nested under another sub-menu. https://i.sst ...

Mounting a Vue3 component within an established application: Step-by-step guide

Imagine we have already mounted an App in main.js: createApp(App).mount('#app'); Now, I want to create a function that is called like this: createModal({ render: () => <SomeComponent />, }); Typically, we would impl ...

Why does the hashtag keep popping up every time I launch the Bootstrap Modal?

I can't figure out why this keeps happening. I researched how to eliminate hashtags from the URL and found multiple solutions. However, none of them proved to be helpful as they only removed the hashtag, requiring a page refresh which still didn' ...

Experiencing difficulty verifying credentials with passport following the code restructuring

Working on developing a RESTful app, I am utilizing node.js, mongoose, express & passport with .ejs for the front end. My current challenge lies in reintegrating authentication with passport. The issue at hand is that although I can successfully regist ...

MUI: Issue with pseudo element appearing cropped outside of Paper container

I am facing an issue where a red arrow pseudo element '::before' is partially cut off outside its container '.MuiPaper-root'. I need the arrow to remain visible, any suggestions on how to fix this? Here is the relevant code snippet and ...

Utilize the power of modern Javascript to extract and display data from a JSON file by mapping an array and adding it

I've been attempting to construct a table from a JSON file by utilizing the map method in React. I've experimented with two approaches - one using map and the other using a for loop - but so far, I haven't been successful in getting the desi ...

Is npm bundled with node-gyp?

I am currently experiencing an issue where running npm install locally does not produce much output when using npm v6.14.9. However, when I deploy to the server, it generates some incomprehensible messages like: gyp info spawn args ['some properties a ...

The error message in monodb.js at line 2: "require is not defined" indicates an issue with the 'require' statement not being

const { MongoClient } = require("mongodb") const url='mongodb://localhost:27017' const client=new MongoClient(url); async function fetchData(){ let result=await client.connect(); let db=result.db("first& ...

Utilizing arrays for generating tables in React

I needed to design a table using data retrieved from an API, where only specific columns should be visible by default. Here are two arrays, one containing the default column headers for the table and the other containing the id and title of the data: const ...

I am interested in dynamically rendering the page on Next.js based on certain conditions

In my -app.js file, I have the code snippet below: import { useState, useEffect } from "react"; import PropTypes from "prop-types"; ... export default function MyApp(props) { const { Component, pageProps } = props; co ...

Is there a way to reach a different function within the value of the react Context.Provider?

Right now, I am learning how to utilize the react context API. Within my react Provider class, I have some state data and functions stored in the value={}. But I am curious, how can I call a function inside this value from another function within the same ...

Verify if session is in existence

Currently in the process of setting up my NodeJS and Express App, utilizing Passport for authentication through Google Sign In and Login. All functionalities work flawlessly when tested on localhost. The sign-in process is smooth, and upon checking, I can ...

Manipulate image position with touchmove event using CSS3 transformations on an iPad

Looking to adjust the position of an image on my iPad3, but running into some difficulties. The movement isn't as smooth as desired and seems to lag behind the gestures being made. This is what I have so far (a 3MB base64 image) <img src="data:i ...

The scenario of the variable name being included rather than its actual value is occurring within a

Encountering an issue with adding values to a JavaScript object: the value to be added is a key,value pair. Here's a snippet of the problem: //JavaScript object var cart=new Object(); function add() { var rating="1" var category="somecat"; va ...

Revise the reply within ExpressJS

I need help with editing the response to a request in Express. When the request is made via XHR, I want to encapsulate the body inside a JavaScript object. This way, different parts of the page can be accessed individually within the JavaScript object, suc ...

sequencing the compilation of Node.js modules

I am facing an issue with my node application involving multiple interdependent modules exported using module.exports. These modules include mongohelper, transaction, server, conhandlr, and appmin. Compile order- mongohelper transaction server (..the ...

React: executing function before fetch completes

Whenever I trigger the ShowUserPanel() function, it also calls the getUsers function to retrieve the necessary data for populating the table in the var rows. However, when the ShowUserPanel function is initially called, the table appears empty without an ...