Technologies:
Tolerim
2 hours ago
The audio assets cannot be located on the React App running on Vite.
localhost:5173/assets/Sounds/tink.wav 404 (Not Found)
import { useEffect } from "react";
import './App.css'
import Key from "./Keys/Key"
function App() {
const soundPath = "../assets/Sounds";
function playSound(keyCode) {
let soundName = '';
switch (keyCode) {
case 65:
soundName = 'clap';
break;
case 83:
soundName = 'hihat';
break;
case 68:
soundName = 'kick';
break;
case 70:
soundName = 'openhat';
break;
case 71:
soundName = 'boom';
break;
case 72:
soundName = 'ride';
break;
case 74:
soundName = 'snare';
break;
case 75:
soundName = 'tom';
break;
case 76:
soundName = 'tink';
break;
default:
return;
}
const audio = new Audio(`${soundPath}/${soundName}.wav`);
audio.currentTime = 0;
audio.play();
}
function handleKeyDown(event) {
console.log(event.keyCode);
const audioElement = document.querySelector(`audio[data-key="${event.keyCode}"]`);
if (audioElement) {
playSound(event.keyCode);
} else {
return;
}
}
useEffect(() => {
window.addEventListener('keydown', handleKeyDown);
return () => {
window.removeEventListener('keydown', handleKeyDown);
};
}, []);
return (
<>
<div className="keys">
<Key dataKey="65" kbdName="A" soundName="clap" />
<Key dataKey="83" kbdName="S" soundName="hihat" />
<Key dataKey="68" kbdName="D" soundName="kick" />
<Key dataKey="70" kbdName="F" soundName="openhat" />
<Key dataKey="71" kbdName="G" soundName="boom" />
<Key dataKey="72" kbdName="H" soundName="ride" />
<Key dataKey="74" kbdName="J" soundName="snare" />
<Key dataKey="75" kbdName="K" soundName="tom" />
<Key dataKey="76" kbdName="L" soundName="tink" />
</div>
</>
)
}
export default App
import classes from "./Key.module.css"
import Sound from "../Audio/Sound";
const Key = props => {
const src= `../../assets/Sounds/${props.soundName}.wav`
return (
<div data-key={props.dataKey} className={classes.key}>
<kbd>{props.kbdName}</kbd>
<span className={classes.sound}>{props.soundName}</span>
<Sound data-key={props.dataKey} src={src}/>
</div>
);
}
export default Key;
const Sound = props => {
return (
<audio data-key={props.dataKey} src={props.src}></audio>
);
}
export default Sound;
Answers(1)
Tolerim
2 hours ago
Verified Answer
The issue is with the path of the sound files. The sound files should be stored in a public folder to be properly served by the Vite server. You can then reference the sounds using the relative path from the public folder, like this "/assets/Sounds/clap.wav".
Here's how you can modify your code to fix the issue:
- Move the Sounds folder to the public folder. The sound files should be located at public/assets/Sounds.
- Update the soundPath variable in your App.js file to "/assets/Sounds"
- Update the src variable in your Key.js file to "/assets/Sounds/${props.soundName}.wav"
After making these changes, your sound files should be accessible and the errors should go away.