6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【React】HTML5のaudio要素で音楽を順番に再生する

Last updated at Posted at 2018-08-02

Reactでライブラリ使わず、音楽を順番に再生させたいと思ったのでやってみました。

ソースコード
MusicPlayerコンポーネントに音楽のデータの配列を渡します。

App.js
import React, { Component } from 'react';
import MusicPlayer from './components/musicPlayer';

class App extends Component {
  render() {
    const musics = [
      {
        id: 1,
        src: "http://~/~.mp3"
      },
      {
        id: 2,
        src: "http://~/~.mp3"
      }
    ];
    return (
      <div>
          <MusicPlayer musics={musics} />
      </div>
    );
  }
}

export default App;

MusicPlayerコンポーネントで、音楽のデータの配列からMusicコンポーネントにデータを渡す。
そして、順番に音楽が流れるようにする。

components/musicPlayer.js
import React, { Component } from 'react';
import Music from './music';
export default class MusicPlayer extends Component {
  constructor(props) {
    super(props);
  }
  playMusic() {
    let musics = document.getElementsByClassName("music");
    musics =  Array.prototype.slice.call(musics);
    const playMusic = (n) => {
      musics[n].play();
      musics[n].addEventListener("ended",() => {
        if (n < musics.length) {
          playMusic(n + 1);
        }
      });
    }
    playMusic(0);
  }
  componentDidMount() {
    this.playMusic();
  }
  render() {
    return this.props.musics.map((music) => <Music {...music} />);
  }
}

Musicコンポーネントで、audio要素を作る。

components/music.js
import React from 'react';

const Music = (props) => {
  return <audio {...props} className="music" />;
}

export default Music;

ソースコード

6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?