I'm making a React app and I want to be able to play audio. I'm using nuka-carousel
to make a carousel, and on each slide I want to play a different sound.
I just can't seem to get the audio playing (ideally autoplay) at all. I tried using the <audio>
tag with the <source>
tags inside and that didn't seem to work, and neither did using <audio src="...", autoPlay>
, as suggested by another StackOverflow post. All of those resulted in just the controls displaying if I enabled the controls
tag but I couldn't even press the play button. I tried react-audio-player
and that gave the same result.
This is what shows up and this is the code for all 3 of those:
This is the code for that
function App() {
return (
<div>
<audio src="..." controls/>
<audio controls>
<source src="..."/>
</audio>
<ReactAudioPlayer src="..." controls>
</ReactAudioPlayer>
</div>
);
}
I also tried using Howler, but with that I found out that I basically need to either have a button to play the sound (I tried making it so that it would autoplay, but for some reason it resulted in the sound playing every time I clicked the page, and I have no idea why). Here's what I have with Howler:
function SoundPlay(src){
const sound = new Howl({
src,
autoplay: true,
onend: function(){
console.log("done");
}
})
sound.play();
}
//soundObj is just an object with the sound source and its label
function RenderButtonAndSound(){
return(
<button key={index} onClick={() => SoundPlay(soundObj.sound)}>
{soundObj.label}
</button>
)
})
}
function Slide1(){
return(
<div>
this is the first slide
{SoundPlay(moon)};
</div>
)
}