Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use howler.js in react?

Why is it that when I click play, I can play the sound and when I click play, there is no sound??

import React, { Component } from "react";
import { Howl, Howler } from 'howler';

class App extends Component {
  SoundPlay() {
    const Sounds = new Howl({
      src: ["sound.mp3"]
    })
    Sounds.play()
    console.log("sound")
  }
  render() {
    return (
      <div className="App">
        <button onClick={this.SoundPlay}>play</button>
      </div>
    );
  }
}

export default App;
like image 634
张晓钒 Avatar asked Feb 26 '19 13:02

张晓钒


People also ask

How does howler JS work?

Howler. js offers a consistent API for using audio with JavaScript, with control over common audio patterns including play, pause, seek to rate, fade and loop. Audio files are automatically cached where possible to improve playback performance.

Can I use JavaScript in react?

It is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript. JSX produces React “elements”.


1 Answers

I recently published react-use-audio-player which is a react hooks abstraction of howlerjs. You can use it like so:

import { useAudioPlayer } from "react-use-audio-player"

function MyComponent() {
    const { play, pause, stop, playing } = useAudioPlayer()

    const handlePlayPause = () => {
        if (playing) {
            pause()
        } else {
            play()
        }
    }

    return (
        <div className="audioControls">
            <button onClick={handlePlayPause}>
                {playing ? "pause" : "play"}
            </button>
            <button onClick={stop}>stop</button>
        </div>
    )
}
like image 151
kuersch Avatar answered Oct 22 '22 10:10

kuersch