LoginSignup
1
1

More than 3 years have passed since last update.

Laravel8 + React + web audio API で音を出す

Last updated at Posted at 2021-01-24

目的

素人向けの記事がなかったので作成。
webで音声周りでやりたいことができたのでweb audio APIを使う。
この記事で公開されている「Web Audio APIで単一サウンドを再生」を行う。

(※) サーバー周りをまだ試していないのでLaravelの解説はしない。あくまで動いたよ!という報告だけ。

前提

  • Laravel8 + ReactでExample.jsを表示できたよ!という状態

手順

まずはnpmでインストール。しようとしたが、以下のようなエラーが出る。

$ npm install react-webaudio
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: XXXXXXXXXXXXXXXXX@undefined
npm ERR! Found: react@16.14.0
npm ERR! node_modules/react
npm ERR!   dev react@"^16.2.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer react@"0.14.0" from react-webaudio@0.3.0-EXPERIMENTAL

Laravel uiのReactバージョンが16.14.0でweb Audioで要求されているバージョンが16.2.0だよ!ということらしい。
マイナーバージョンの差だし大丈夫でしょ!
動かなかったら考える理論で強制インストール。
ダメだった場合はバージョンを指定してReactをインストールし直しましょう。

$ npm install --legacy-peer-deps react-webaudio

今回は音を鳴らすだけなので上記の記事を参考に、少し改変して Example.jsを以下のように修正。

Example.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Button} from '@material-ui/core';

const audioController = (() => {
    const context = new AudioContext();
    const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    const channels = 2;
    const frameCount = audioCtx.sampleRate * 2.0;
    const buffer = audioCtx.createBuffer(channels, frameCount, audioCtx.sampleRate);

    for (let channel = 0; channel < channels; channel++) {
      const nowBuffering = buffer.getChannelData(channel);
      for (let i = 0; i < frameCount; i++) {
        nowBuffering[i] = Math.random() * 2 - 1;
      }
    }
    const source = audioCtx.createBufferSource();
    source.buffer = buffer;
    source.connect(audioCtx.destination);
    source.start();
});

function Example() {
    return (
        <div className="container">
            <div className="row justify-content-center">
                <div className="col-md-8">
                    <div className="card">
                        <Button onClick={audioController}>On</Button>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default Example;
if (document.getElementById('app')) {
    ReactDOM.render(<Example />, document.getElementById('app'));
}

コツは必ずアロー関数で宣言することである。

ビルドしたあとは画面に表示された「On」をクリックして「サーッ」と音が鳴ればOK。
色々できそうなAPIなので触って試してみたい。

追記(2020/2/4)

material-ui を追加していない場合はインストールしましょう

$ npm install @material-ui/core
1
1
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
1
1