LoginSignup
18
20

More than 5 years have passed since last update.

iPhoneのSafariに対応した音声レコーダーを作成する方法

Posted at

概要

iPhoneのSafariに対応したレコーダーを作成する方法を紹介します。

動作環境

  • iOS11.4

前提条件

  1. マイク、カメラにアクセスするためにはhttpsのサイトであることが必須条件
  2. iPhoneでのブラウザはSafariのみ対応

ポイント

  1. getUserMediaを呼び出す前にAudioContextを作成する。

実装

上記のポイントを踏まえて実装したものは以下のようになります

startRecord
 function startRecording(evt_stream) {

     // 取得されている音声ストリームの録音を開始
     localMediaStream = evt_stream;

     if (!navigator || !navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
       alert('Missing support for navigator.mediaDevices.getUserMedia') // temp: helps when testing for strange issues on ios/safari
       return
     }

     audioContext = new (window.AudioContext || window.webkitAudioContext)();
     // サンプルレートを保持しておく
     audioSampleRate = audioContext.sampleRate;

     let scriptProcessor = audioContext.createScriptProcessor(bufferSize, 1, 1);
     localScriptProcessor = scriptProcessor;

     if (audioContext.createMediaStreamDestination) {
       destinationNode = audioContext.createMediaStreamDestination()
     }
     else {
       destinationNode = audioContext.destination
     }

     // safariで Web Audio APIを動かすため、先にaudioContextを生成してから、UserMediaを生成する
     return navigator.mediaDevices.getUserMedia({audio: true})
       .then((stream) => {
         this._startRecordingWithStream(stream, destinationNode, scriptProcessor)
       })
       .catch((error) => {
         alert('Error with getUserMedia: ' + error.message) // temp: helps when testing for strange issues on ios/safari
         console.log(error)
       })
   }
_startRecordingWithStream
   function _startRecordingWithStream(stream, destinationNode, scriptProcessor) {
     // ループ処理のセット
     let mediastreamsource = audioContext.createMediaStreamSource(stream);
     mediastreamsource.connect(scriptProcessor);
     scriptProcessor.onaudioprocess = onAudioProcess;
     console.log('レコードスタート: scriptProcessor.connect(audioContext.destination)');
     scriptProcessor.connect(destinationNode);
   }

また、実装に伴ったソースコード並びにサンプルも用意しました。

サンプルコード
サンプル

参考

18
20
1

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
18
20