I'm working on a Next.js application that includes playing audio using the HTML5 Audio API. It works perfectly on desktop browsers, but I'm encountering issues when trying to play audio on mobile devices (both iOS and Android). The audio does not play, and there are no error messages in the console.
Here's a simplified version of the code I'm using:
import { useEffect } from "react"
const AudioPlayer = () => {
useEffect(() => {
const audio = new Audio("/path/to/audio/file.mp3")
audio.play().catch(error => {
console.error("Error playing audio:", error)
});
}, []);
return <div>Audio Player</div>
};
export default AudioPlayer
I've tried the following solutions without success:
Has anyone faced a similar issue or have any suggestions on how to resolve this?
Thanks in advance!
Could you test this.
import { useState } from "react";
const AudioPlayer = () => {
const [audio] = useState(new Audio("/path/to/audio/file.mp3"));
const playAudio = () => {
audio.play().catch(error => {
console.error("Error playing audio:", error);
});
};
return (
<div>
<button onClick={playAudio}>Play Audio</button>
</div>
);
};
export default AudioPlayer;