What's causing this slow/delayed audio playback in Safari?

末鹿安然 提交于 2020-08-25 04:07:09

问题


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:

  1. With HTML5 audio tag, if the audio is less than 500ms, the volume in Safari might fluctuate with all formats
  2. With HTML5 audio tag, the delay is obvious with all formats
  3. With flash audio player, the delay is obvious with *.wav, but it's fine with *.mp3

Considering on other platforms:

  1. IE9 doesn’t support native audio tag
  2. Firefox’s audio sounds terrible when html5 audio tag is used with mp3/ogg format, but is okay with wav.
  3. Firefox is fine with flash audio player

To achieve compatibility across all browsers:

  1. Use flash audio player
  2. Use mp3 and wav format
  3. Put mp3 before wav

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!