如何使用 Javascript 在移动 Safari 和所有其他浏览器上录制音频?
Posted
技术标签:
【中文标题】如何使用 Javascript 在移动 Safari 和所有其他浏览器上录制音频?【英文标题】:How to record audio at mobile Safari and all other browsers with Javascript? 【发布时间】:2019-05-19 08:52:39 【问题描述】:我只想在所有浏览器、桌面浏览器以及移动 (ios/android) 浏览器中录制音频。
我已经编写了一些在桌面 Chrome 浏览器中运行的 javascript。但是当我在带有 Safari/Chrome 的 iPhone 7 上尝试这个时;它不工作。
据我了解,这与不同的移动浏览器 API 有关。所以我需要更改代码,使其支持所有类型的浏览器 API。
如何更改代码以支持所有浏览器?
'use strict'
var log = console.log.bind(console),
id = val => document.getElementById(val),
ul = id('ul'),
gUMbtn = id('gUMbtn'),
start = id('start'),
stop = id('stop'),
stream,
recorder,
counter = 1,
chunks,
media;
var mv = id('mediaVideo'),
mediaOptions =
video:
tag: 'video',
type: 'video/webm',
ext: '.mp4',
gUM: video: true, audio: true
,
audio:
tag: 'audio',
type: 'audio/ogg',
ext: '.ogg',
gUM: audio: true
media = mediaOptions.audio;
navigator.mediaDevices.getUserMedia(media.gUM).then(_stream =>
stream = _stream;
id('btns').style.display = 'inherit';
start.removeAttribute('disabled');
recorder = new MediaRecorder(stream);
recorder.ondataavailable = e =>
chunks.push(e.data);
let blob = new Blob(chunks, type: media.type )
, url = URL.createObjectURL(blob)
, li = document.createElement('li')
, mt = document.createElement(media.tag)
, hf = document.createElement('a');
if (recorder.state == 'inactive') makeLink(url, li, mt, hf);
let reader = new FileReader();
reader.addEventListener('load', e=>
var url = "http://localhost:8080/rest/api/v1/audio/submit";
var payload = '"recording":"'+reader.result+'"';
var xhttp = new XMLHttpRequest();
xhttp.open("POST",url,true );
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send(payload);
);
reader.readAsDataURL(blob);
;
).catch(log);
start.onclick = e =>
start.disabled = true;
stop.removeAttribute('disabled');
chunks = [];
recorder.start();
stop.onclick = e =>
stop.disabled = true;
recorder.stop();
start.removeAttribute('disabled');
function makeLink(url, li, mt, hf)
mt.controls = true;
mt.src = url;
hf.href = url;
hf.download = `$counter++$media.ext`;
hf.innerhtml = `$hf.href`;
li.appendChild(mt);
li.appendChild(hf);
ul.appendChild(li);
【问题讨论】:
你可以先去caniuse.com/#search=MediaRecorder看看哪些浏览器支持录制。然后,前往 MDN 了解 API 在不同浏览器中的工作原理。但它是一个新的 API,所以它不会在任何地方都有效! 【参考方案1】:我认为音频录制仍然无法在 iOS 上使用 Chrome。它确实适用于 safari 浏览器。但是您不能使用 MediaRecorder,而必须使用 Media Capture 和 Streams API。 这是一个链接:https://developer.mozilla.org/en-US/docs/Web/API/Media_Streams_API
【讨论】:
以上是关于如何使用 Javascript 在移动 Safari 和所有其他浏览器上录制音频?的主要内容,如果未能解决你的问题,请参考以下文章
javascript- Safari 上的 getUserMedia