问题
var audio = new Audio('data:audio/wav;base64,UklGRoABAABXQVZFZm10IBAAAAABAAEAiBUAAIgVAAABAAgAZGF0YVwBAACHlqa1xNLg7vv/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////Tk1LSklHRkVEQ0JBQD8+Pj08PDs6Ojk5OTg4ODg3Nzc3Nzc3Nzc3Nzc3Nzg4ODg5OTk6Ojs7Ozw8PT4+P0BAQUJCQ0RFRUZHSElJSktMTU5OT1BRUlNUVVVWV1hZWltcXV1eX2BhYmNkZGVmZ2hpaWprbG1ubm9wcXFyc3R0dXZ3d3h5eXp6e3x8fX1+f3+AgIGBgoKCg4OEhISFhYWGhoaHh4eHh4iIiIiIiIiIiIiIiIiIiIiIiIiIiIeHh4eHhoaGhYWFhISEg4OCgoGBgIA=');
setInterval(function() {
audio.play();
}, 50);
This code works correctly in Chrome and Firefox, but in Safari there's a delay of over a second between each sound. I can't figure out why this would be, as far as I can tell there are no compatibility issues. I want to play sounds at a precise time and at a reasonably fast delay in a game that I'm making, how can I get this working?
回答1:
I have no idea why, but adding AudioContext removes the delay.
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioCtx = new AudioContext();
Found out by accident, works for me. Go figure.
Safari version 12.0 (14606.1.36.1.9).
回答2:
(Copied from the same question I answered just now)
Safari displays curious behaviour when it comes to audio. It seems like:
- With HTML5 audio tag, if the audio is less than 500ms, the volume in Safari might fluctuate with all formats
- With HTML5 audio tag, the delay is obvious with all formats
- With flash audio player, the delay is obvious with
*.wav, but it's fine with*.mp3
Considering on other platforms:
- IE9 doesn’t support native audio tag
- Firefox’s audio sounds terrible when html5 audio tag is used with
mp3/oggformat, but is okay withwav. - Firefox is fine with flash audio player
To achieve compatibility across all browsers:
- Use flash audio player
- Use
mp3andwavformat - Put
mp3beforewav
So with Sound Manager 2:
soundManager.setup({
url: './swf/',
flashVersion: 9,
preferFlash: true,
onready: function() {
soundManager.createSound({
id: "button",
url: ["./audio/button.mp3", "./audio/button.wav"],
autoLoad: true,
autoPlay: false,
volume: volume
});
}
});
And play with:
soundManager.play("button");
This should solve the delay issue with Safari.
来源:https://stackoverflow.com/questions/22216954/whats-causing-this-slow-delayed-audio-playback-in-safari