Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

play sound onload react

import React, { useState, useEffect } from "react";

const useAudio = url => {
  const [audio] = useState(new Audio(url));
  const [playing, setPlaying] = useState(false);

  const toggle = () => setPlaying(!playing);

  useEffect(() => {
      playing ? audio.play() : audio.pause();
    },
    [playing]
  );

  useEffect(() => {
    audio.addEventListener('ended', () => setPlaying(false));
    return () => {
      audio.removeEventListener('ended', () => setPlaying(false));
    };
  }, []);

  return [playing, toggle];
};

const Player = ({ url }) => {
  const [playing, toggle] = useAudio(url);

  return (
    <div>
      <button onClick={toggle}>{playing ? "Pause" : "Play"}</button>
    </div>
  );
};

export default Player;
Comment

play audio in react

import ReactAudioPlayer from 'react-audio-player';
//...
<ReactAudioPlayer
  src="my_audio_file.ogg"
  autoPlay
  controls
/>
Comment

play audio in react

npm install --save react-audio-player
Comment

play sound onload react

class Music extends React.Component {
  state = {
    play: false
  }
  audio = new Audio(this.props.url)

  componentDidMount() {
    audio.addEventListener('ended', () => this.setState({ play: false }));
  }

  componentWillUnmount() {
    audio.removeEventListener('ended', () => this.setState({ play: false }));  
  }

  togglePlay = () => {
    this.setState({ play: !this.state.play }, () => {
      this.state.play ? this.audio.play() : this.audio.pause();
    });
  }

  render() {
    return (
      <div>
        <button onClick={this.togglePlay}>{this.state.play ? 'Pause' : 'Play'}</button>
      </div>
    );
  }
}

export default Music;
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript operators 
Javascript :: js array split 
Javascript :: remove array from array javascript 
Javascript :: var function js 
Javascript :: create slice redux 
Javascript :: how to read excel file in nodejs 
Javascript :: adding pre tag javascript 
Javascript :: objects in array 
Javascript :: sort an array 
Javascript :: check if property has value in array javascript 
Javascript :: spotify player react 
Javascript :: scroll position 
Javascript :: moment isbetween 
Javascript :: what is let js 
Javascript :: reference data types in javascript 
Javascript :: reduce function in javascript 
Javascript :: javaScript Math.log() Method 
Javascript :: double bang js 
Javascript :: javascript error null 
Javascript :: como agregar items en un array javascript 
Javascript :: quadratic equation in js by function 
Javascript :: dark mode javascript 
Javascript :: Dynamically load JS inside JS 
Javascript :: favicon express js 
Javascript :: Check if a number is even or odd 
Javascript :: formidable form node js 
Javascript :: canvas container page offset 
Python :: ignore warnings 
Python :: tkinter always on top 
Python :: legend size matplotlib 
ADD CONTENT
Topic
Content
Source link
Name
3+1 =