LoginSignup
5
3

More than 3 years have passed since last update.

【日本語変数名で学ぶ】 音を鳴らすタイミングをawaitで管理する

Last updated at Posted at 2019-09-19

よい人事とは何か考える日々を送っています。GENYAです。

動くもの
https://codesandbox.io/s/sound-promise-quwxm

課題感

Web Audio API を使って音を鳴らす仕組みを作っていて
音のタイミングを測りながら調整するときにasync/awaitを使いたかったがnew audio().play()はpromiseを返していなかった。

実装したこと

音のタイミング管理をpromiseベースで実装した。

タイミングを測る部分についてはタイミング調整時にわかりやすいよう羅列して書くようにする。


// ----- sound.js
const 音源のURL =
  "https://raw.githubusercontent.com/wilf312/test/master/docs/trumpet1.mp3";

const オーディオAPI = new Audio(音源のURL);

export const 音を鳴らす = () => {
  return new Promise(resolve => {
    オーディオAPI.onended = resolve;

    オーディオAPI.play();
  });
};


export const 待つ = (time: number) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve();
    }, time);
  });
};


// ----- index.js
import { 音を鳴らす} from "./sound";

// 実際のタイミングを制御する関数
const 実行 = async () => {
  await 待つ(1500);
  await 音を鳴らす();
  await 待つ(5000);
  await 音を鳴らす();
};

実行();

まとめ

実行関数 部分に どのタイミングで音を鳴らすかの制御をまとめることで管理を楽にできるようになりました。
音を鳴らすこと自体が実装していて少なかったのですが、
今回触ってみて楽しかったので良かったら参考にしてみてください。

5
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
5
3