HTML 5でのAudio使用ピットまとめ
8471 ワード
var playPromise = document.querySelector('video').play();
// In browsers that don’t yet support this functionality,
// playPromise won’t be defined.
if (playPromise !== undefined) {
playPromise.then(function() {
// Automatic playback started!
}).catch(function(error) {
// Automatic playback failed.
// Show a UI element to let the user manually start playback.
});
}
参考資料:HTML MediaElement.play() Returns a Promise media .
currentTime
[ = value ] Returns the current playback position, in seconds.
Can be set, to seek to the given time.
Will throw an
INVALID_STATE_ERR
exception if there is no selected media resource. Will throw an INDEX_SIZE_ERR
exception if the given time is not within the ranges to which the user agent can seek. playButton.addEventListener("click", () => {
audioElem.play()
}, false);
//
playButton.addEventListener("click", () => {
setTimeout(() => {
audioElem.play()
}, 100)
}, false);
の場合、一部のバージョン【iOS 120.0.1親測有坑】でもNotAllowedError異常がトリガーされる場合があり、これを回避すべきであり、// hack
playButton.addEventListener("click", () => {
audioElem.muted = true
let p = audioElem.play()
if (p !== undefined) {
p.then(() => {
audioElem.muted = false
audioElem.pause()
setTimeout(() => {
audioElem.play()
}, 100)
}).catch((e) => {
console.log(e)
})
}
}, false);
playButton.addEventListener("click", () => {
audioElem.src = "https://a.mp3"
audioElem.play()
}, false);
// , src play
audioElem.src = "https://b.mp3"
audioElem.play()
audioElem.play()
を呼び出しただけで、間違いを投げ出すことはありませんが、audioは実際には本当に再生されていません.音はありません.//
addPageVisibilityListener(() => {
//
audioElem.pause()
},() => {
//
// src
audioElem.src = "https://b.mp3"
audioElem.play()
// load
// audioElem.load()
// audioElem.play()
})
解決:この2つの異常な動作はiOS 12.0.1システム自体のバグであるべきである.この2つの異常の発生を回避するには、次の2つの方法があります.
const playAudio = () => {
audioElem1.removeEventListener('canplaythrough', playAudio)
let p = audioElem.play()
if (p !== undefined) {
p.catch((e) => {
console.log(e)
})
}
}
//
addPageVisibilityListener(() => {
//
audioElem.pause()
},() => {
//
audioElem.load()
audioElem.addEventListener('canplaythrough', playAudio)
})
let playAudio = (retry: boolean) => {
let p = audioElem.play();
if (p !== undefined) {
p.catch((e) => {
if (retry) {
setTimeout(() => {
playAudio(false);
}, 0);
}
});
}
}
//
addPageVisibilityListener(() => {
//
audioElem.pause()
},() => {
//
setTimeout(() => {
playAudio(true)
}, 500)
})