我有一个 onclick 事件,可以切换页面加载的一些音频。问题是它适用于除某些选定的 iPhone 之外的所有浏览器和设备。例如,它适用于 iPhone 11,但不适用于 iPhone 7。
<img id="play" class="play_pause_button" src="" onclick="play();">
var audio1 = {
playing: !1,
gainNode: null,
play: function () {
context.createGain || (context.createGain = context.createGainNode), (this.gainNode = context.createGain())
var t = context.createBufferSource()
;(t.buffer = bufferList[0]), t.connect(this.gainNode), this.gainNode.connect(context.destination), (this.gainNode.gain.value = 0.5), (t.loop = !0), t.start || (t.start = t.noteOn), t.start(0), (this.source = t)
},
changeVolume: function (t) {
var e = t.value
parseInt(t.value), parseInt(t.max)
this.gainNode.gain.value = e
},
stop: function () {
this.source.stop || (this.source.stop = source.noteOff), this.source.stop(0)
},
toggle: function () {
this.playing ? this.stop() : this.play(), (this.playing = !this.playing)
}
}
function play() {
audio1.toggle()
}
音频在加载时加载如下:
var context, bufferLoader, bufferList
window.onload = init
var everythingready = !1,
isplaying = !1
function init() {
;(window.AudioContext = window.AudioContext || window.webkitAudioContext),
(context = new AudioContext()),
bufferLoader = new BufferLoader(context, ["https://url-to.mp3"
], finishedLoading).load()
}
function finishedLoading(t) {
(everythingready = !0), (bufferList = t)
}
使用缓冲加载器如下:
function BufferLoader(context, urlList, callback) {
this.context = context;
this.urlList = urlList;
this.onload = callback;
this.bufferList = new Array();
this.loadCount = 0;
}
BufferLoader.prototype.loadBuffer = function(url, index) {
// Load buffer asynchronously
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
var loader = this;
request.onload = function() {
// Asynchronously decode the audio file data in request.response
loader.context.decodeAudioData(
request.response,
function(buffer) {
if (!buffer) {
alert('error decoding file data: ' + url);
return;
}
loader.bufferList[index] = buffer;
if (++loader.loadCount == loader.urlList.length)
loader.onload(loader.bufferList);
},
function(error) {
console.error('decodeAudioData error', error);
}
);
}
request.onerror = function() {
alert('BufferLoader: XHR error');
}
request.send();
}
BufferLoader.prototype.load = function() {
for (var i = 0; i < this.urlList.length; ++i)
this.loadBuffer(this.urlList[i], i);
}
此代码在桌面浏览器、Android 设备和部分 iPhone 上都能完美运行。我不知道为什么它不适用于某些 iPhone。任何帮助将不胜感激。