-
Notifications
You must be signed in to change notification settings - Fork 1
/
autostart.js
109 lines (98 loc) · 3.85 KB
/
autostart.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
if (typeof AudioContext !== "undefined")
{
AudioContext = (function (AudioContext)
{
var buttonText = document.currentScript.getAttribute("data-btn-label") || "Start audio";
var timeout = parseFloat(document.currentScript.getAttribute("data-timeout")) || 0;
var OriginalAudioContextCtor = AudioContext;
// Replace the 'AudioContext' constructor with one that automatically calls the 'resume()' method.
// If needed, this will show a "toast" message near the bottom of the screen.
AudioContext = function ()
{
let audioCtx = new OriginalAudioContextCtor();
if (audioCtx.state === "running")
{
return audioCtx;
}
// It could be that 'new AudioContext()' is already called in response to a user triggered action, in which case we don't
// need to show an initializer toast at all. Try doing this first.
audioCtx.resume();
window.setTimeout(function ()
{
if (audioCtx.state === "suspended")
{
// Alright, this didn't work, so let's try again through the toast or by waiting.
if (timeout > 0)
{
// Wait for a user gesture to happen in the document (can work with kDocumentUserActivationRequired policy).
waitAutoStart(audioCtx, performance.now() + timeout, function ()
{
// Fail callback, could not auto-start.
showToast(buttonText, function ()
{
audioCtx.resume();
});
});
}
else
{
showToast(buttonText, function ()
{
audioCtx.resume();
});
}
}
}, 100);
return audioCtx;
}
function showToast(buttonText, callback)
{
var toast = document.createElement("div");
toast.style.position = "absolute";
toast.style.right = "0px";
toast.style.bottom = "0px";
toast.style.zIndex = "999";
toast.style.padding = "16px";
toast.style.width = "100%";
toast.style.textAlign = "center";
toast.style.background = "rgb(60,60,60)";
toast.style.boxSizing = "border-box";
toast.style.fontWeight = "100";
toast.style.color = "#eee";
toast.style.fontSize = "16px";
toast.style.boxShadow = "0 3px 6px rgba(0,0,0,0.4)";
toast.style.cursor = "pointer";
toast.innerHTML = buttonText;
toast.className = "audioctx-resume-btn";
window.setTimeout(function ()
{
document.body.appendChild(toast);
toast.addEventListener("click", function ()
{
callback();
document.body.removeChild(toast);
});
}, 0);
}
function waitAutoStart(audioCtx, deadline, fail)
{
audioCtx.resume();
if (audioCtx.state === "suspended")
{
// Still no good, keep trying if we have time.
if (performance.now() < deadline + 100)
{
window.setTimeout(function ()
{
waitAutoStart(audioCtx, deadline, fail);
}, 100);
}
else
{
fail();
}
}
}
return AudioContext;
})(AudioContext);
}