UNPKG

2.4 kBPlain TextView Raw
1import { version } from "../version.js";
2import {
3 AnyAudioContext,
4 hasAudioContext,
5 theWindow,
6} from "./context/AudioContext.js";
7import { Context } from "./context/Context.js";
8import { DummyContext } from "./context/DummyContext.js";
9import { BaseContext } from "./context/BaseContext.js";
10import { OfflineContext } from "./context/OfflineContext.js";
11import {
12 isAudioContext,
13 isOfflineAudioContext,
14} from "./util/AdvancedTypeCheck.js";
15
16/**
17 * This dummy context is used to avoid throwing immediate errors when importing in Node.js
18 */
19const dummyContext = new DummyContext();
20
21/**
22 * The global audio context which is getable and assignable through
23 * getContext and setContext
24 */
25let globalContext: BaseContext = dummyContext;
26
27/**
28 * Returns the default system-wide {@link Context}
29 * @category Core
30 */
31export function getContext(): BaseContext {
32 if (globalContext === dummyContext && hasAudioContext) {
33 setContext(new Context());
34 }
35 return globalContext;
36}
37
38/**
39 * Set the default audio context
40 * @param context
41 * @param disposeOld Pass `true` if you don't need the old context to dispose it.
42 * @category Core
43 */
44export function setContext(
45 context: BaseContext | AnyAudioContext,
46 disposeOld = false
47): void {
48 if (disposeOld) {
49 globalContext.dispose();
50 }
51
52 if (isAudioContext(context)) {
53 globalContext = new Context(context);
54 } else if (isOfflineAudioContext(context)) {
55 globalContext = new OfflineContext(context);
56 } else {
57 globalContext = context;
58 }
59}
60
61/**
62 * Most browsers will not play _any_ audio until a user
63 * clicks something (like a play button). Invoke this method
64 * on a click or keypress event handler to start the audio context.
65 * More about the Autoplay policy
66 * [here](https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio)
67 * @example
68 * document.querySelector("button").addEventListener("click", async () => {
69 * await Tone.start();
70 * console.log("context started");
71 * });
72 * @category Core
73 */
74export function start(): Promise<void> {
75 return globalContext.resume();
76}
77
78/**
79 * Log Tone.js + version in the console.
80 */
81if (theWindow && !theWindow.TONE_SILENCE_LOGGING) {
82 let prefix = "v";
83 if (version === "dev") {
84 prefix = "";
85 }
86 const printString = ` * Tone.js ${prefix}${version} * `;
87 // eslint-disable-next-line no-console
88 console.log(`%c${printString}`, "background: #000; color: #fff");
89}