0

I would like a song to play once a user moves the mouse on the landing page of my app. I know about the autoplay policy for most modern browsers that require user interaction before it can play. I wanted to ask how to achieve this with a "global event listener" - as long as the user does anything on the page (eg move mouse) the song starts.

Here's what I have but it does not work yet:

import Music1 from './song1.mp3'
import Music2 from './song2.mp3'
import React from 'react'
// import Sound from 'react-sound'
import ReactAudioPlayer from 'react-audio-player';


const AudioPlayer = ({ Music }) => {
  if (Music == null) {
    Music = Music1;
  }

  let hasMouse = false;
  console.log ('before move' + hasMouse)
  const hasMouseCheck = () => {
      hasMouse = true;
      // Kill the event listener, so it executes only once
    window.removeEventListener('mousemove', hasMouseCheck, false);
    console.log ('after move' + hasMouse); // this works and it prints 'true' to the console
  };

  window.addEventListener('mousemove', hasMouseCheck, false);
  
  return (


    <>
      {hasMouse && 
      <ReactAudioPlayer
        src={Music}
        autoplay={true}
      preload={'metadata'}
      loop={true}
      />
    }
    </>
    
);

}

export default AudioPlayer;

It does not work. I also tried something like this but that did not work.

<ReactAudioPlayer 
src={Music}
autoplay={true}
preload={'metadata'}
loop={true}
/>

This react component is loaded at the router level and I've done a console.log to test that the hasMouse function works (it does).

<Switch>
 <Route path={["/", "/intro"]} exact>              
  <AudioPlayer Music={Music1} />
 </Route>
</Switch>

What can I do to make the music play when the user interacts with the page?

(I've read this:Is there a way to auto play audio in React without using an onClick event? but doesn't answer my qn)

yoda79
  • 37
  • 2
  • 10

1 Answers1

0

you should use this property

autoPlay={this.state.autoPlay}

and handle this state for handle mouse

onMouseEnter
onMouseMove
onMouseLeave

onMouseEnter={this.enterMouse}
onMouseLeave={this.leaveMouse}

for the function of these

const enterMouse=()=>{
    setState({
       autoPlay:true
      }    
    }
  • Thanks but that isn't the problem. The problem is that even after the hasMouse flag turns from false to true (which is what you're trying to do), the autoplay does not start. The problem seems to be something else. – yoda79 Jul 13 '21 at 07:05