Play songs one after another with Howler and NextJS

1k Views Asked by At

I have a list of songs on github, the goal is to play all songs one by one and post messages in console. But I faced a problem, how to find if the song is finished? Otherwise my code tries to play all songs without waiting the song's end.

import { Howl } from 'howler'
import { useState } from 'react'

export default function PlaySound() {
  let [initSong, updatedSong] = useState(0)
  const songs = [
    'https://raw.githubusercontent.com/Sound/master/play1.mp3',
    'https://raw.githubusercontent.com/Sound/master/play2.mp3',
    'https://raw.githubusercontent.com/Sound/master/play3.mp3',
    'https://raw.githubusercontent.com/Sound/master/play4.mp3',
    'https://raw.githubusercontent.com/Sound/master/play5.mp3',
  ]

  var sound = new Howl({
    src: songs[initSong],
  })

  function postAMessage() {
    for (let i = 0; i < songs.length; i++) {
      if (initSong >= songs.length) return
      console.log('New song ' + i)
      sound.play()
      updatedSong(initSong++)
      i++
    }
  }

  return (
    <div>
      <button onClick={postAMessage}>Play</button>
    </div>
  )
}
1

There are 1 best solutions below

0
On

can you try react-Howler

import React from "react";
import ReactHowler from "react-howler";
import Button from "../components/Button";

class OnlyPlayPauseButton extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      playing: false
    };
    this.handlePlay = this.handlePlay.bind(this);
    this.handlePause = this.handlePause.bind(this);
  }

  handlePlay() {
    this.setState({
      playing: true
    });
  }

  handlePause() {
    this.setState({
      playing: false
    });
  }

  render() {
    return (
      <div>
        <ReactHowler
          src={["sound.ogg", "sound.mp3"]}
          playing={this.state.playing}
        />
        <Button onClick={this.handlePlay}>Play</Button>
        <Button onClick={this.handlePause}>Pause</Button>
      </div>
    );
  }
}

export default OnlyPlayPauseButton;

refer: https://www.npmjs.com/package/react-howler