0

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: enter image description here

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>
    )
} 
EkLuthra
  • 147
  • 1
  • 9
  • What happens when you use this `` – Hassan Imam Nov 27 '21 at 17:09
  • From the screenshot, it looks like your audio file doesn't exist. Also, chrome has put in policy to avoid autoplaying audio. You can explore [solutions here](https://stackoverflow.com/questions/50490304/how-to-make-audio-autoplay-on-chrome/51630171#51630171) – Hassan Imam Nov 27 '21 at 17:19
  • @HassanImam I used the same filepath for Howler that I did with the ```audio``` tag and it played the audio, just not how I wanted it to – EkLuthra Nov 27 '21 at 22:55
  • @HassanImam when I use `````` it still just displays the same thing as the screenshot shows – EkLuthra Nov 27 '21 at 22:56
  • https://codesandbox.io/s/persistent-audio-player-on-route-change-h2rnx. Try this and let me know if this helps. – Siddharth Varangaonkar Nov 28 '21 at 03:39

0 Answers0