admin管理员组

文章数量:1291029

I am making a piano app. I have a js function in a react ponent that plays the corresponding file to the note provided but the console always throws this error:

Uncaught (in promise) DOMException: The media resource indicated by the src attribute or assigned media provider object was not suitable.

And no sound is played. Here is the function:

var handleClick = (note) => {
    var path = "../../public/notes/" + note + ".mp3";
    var audio = new Audio(path);
    audio.play(); 
    console.log(audio);
    return audio.play();
  };

Also my file structure is:

App
 public
 node_modules
 src
   Components 
          Piano.js

I am making a piano app. I have a js function in a react ponent that plays the corresponding file to the note provided but the console always throws this error:

Uncaught (in promise) DOMException: The media resource indicated by the src attribute or assigned media provider object was not suitable.

And no sound is played. Here is the function:

var handleClick = (note) => {
    var path = "../../public/notes/" + note + ".mp3";
    var audio = new Audio(path);
    audio.play(); 
    console.log(audio);
    return audio.play();
  };

Also my file structure is:

App
 public
 node_modules
 src
   Components 
          Piano.js
Share Improve this question edited Feb 21, 2022 at 15:41 the Hutt 18.4k2 gold badges18 silver badges49 bronze badges asked Feb 13, 2022 at 12:38 ArezeAreze 911 gold badge1 silver badge6 bronze badges 1
  • can you share minimal reproducible on codesandbox? – the Hutt Commented Feb 21, 2022 at 15:42
Add a ment  | 

8 Answers 8

Reset to default 2

Make sure your mp3 files are encoded as per these specifications. You can use any offline or online tool to check your file info.
Maybe you've just renamed the extension to mp3 of some other audio file. Can you share your file somewhere?

Also, don't load files when user clicks on piano keys. Try to preload all sound files like this:

// handle all promise rejections
window.onunhandledrejection = function(event) {
  console.log(`Reason: ${event.reason}`,
    ` Return value: ${event.returnValue}`
  );
};


let mouseDown = false;
let sounds = {
  a: "https://freesound/data/previews/448/448573_9311684-lq.mp3",
  b: "https://freesound/data/previews/448/448565_9311684-lq.mp3",
  c: "https://freesound/data/previews/448/448540_9311684-lq.mp3",
  d: "https://freesound/data/previews/448/448600_9311684-lq.mp3",
}

// preload audio files
let promises = [];
Object.keys(sounds).forEach(s => {
  promises.push(new Promise((resolve, reject) => {
    let url = sounds[s];
    sounds[s] = new Audio();
    sounds[s].addEventListener('canplaythrough', resolve, false);
    sounds[s].src = url;
  }));
});

Promise.all(promises).then(() => {
  stats.innerText = `All audio files loaded!  Drag mouse over the keys 

本文标签: javascriptReact js audio object not playingThe media resource was not suitableStack Overflow