How to record audio on webpage (iOS, Android, PC/M

2019-01-16 10:39发布

问题:

I have a requirement to allow a user to record an audio file using their microphone, but it has to work without flash as it needs to work on iOS (mobile safari), Android browser or Chrome, and a modern browser on a PC/Mac.

Is there a clean, simple HTML5 method for recording audio and posting to a server? I haven't been able to find anything.

回答1:

You can use the HTML5 WebAudio API.

An introduction to audio and video capturing Capture audio & video in HTML5

A good library to record audio with samples Recorder.js

A complete and working sample using Recorder.js How to record audio in Chrome with native HTML5 APIs

Other WebAudio API demos HTML5 Web Audio API Demos and Libraries

Supported browsers Can I use Web Audio API?

Regarding to send the data to other server, using Recorder.js you can get the audio buffer, then you could use XMLHttpRequest to POST the arraybuffer or blob to the destination server directly or encoded as base64.

MDN: Sending and Receiving Binary Data

Html5Rocks: New trick ins XMLHttpRequest2, sending data



回答2:

Professionally speaking I would say no, there are audio APIs for HTML5 but their implementation varies across browsers at the moment. If you're doing this for a tech demo of sorts then that might suffice but otherwise you might need to fall back to other technologies like flash and/or native apps for more reliable results.



回答3:

getUserMedia() is now widely supported across mobile:

  • Safari on iOS 11 (except UIWebView)
  • Chrome on Android

and desktop:

  • Safari 11
  • Chrome
  • Firefox
  • Edge 12
  • Opera

Once webcam/mic permission is given and the mic data kicks in you can:

  • encode the sound using JS libraries like Recorder.js (wav), WebAudioRecorder.js (wav,mp3,Vorbis) or vmsg (mp3).
  • or use the (native) Media Recorder API to capture Opus audio in .ogg (Firefox) and .webm (Chrome) files together with this neat polyfill for Safari 11 and Edge that produces .wav files.

Here's a demo I made (live demo, source on GitHub) that uses Matt Diamond's Recorder.js to record audio (pcm in .wav files) running in Safari on iOS 11. Clicking Record prompts the user to allow microphone access: