Tone.js/Tone/core/Global.ts

80 lines
2.3 KiB
TypeScript
Raw Normal View History

2019-05-23 18:00:49 +00:00
import { version } from "../version";
import { AnyAudioContext, hasAudioContext, theWindow } from "./context/AudioContext";
import { Context } from "./context/Context";
import { DummyContext } from "./context/DummyContext";
import { BaseContext } from "./context/BaseContext";
import { OfflineContext } from "./context/OfflineContext";
import { isAudioContext, isOfflineAudioContext } from "./util/AdvancedTypeCheck";
2019-04-12 14:37:47 +00:00
/**
* This dummy context is used to avoid throwing immediate errors when importing in Node.js
*/
const dummyContext = new DummyContext();
2019-04-12 14:37:47 +00:00
/**
* The global audio context which is getable and assignable through
* getContext and setContext
*/
let globalContext: BaseContext = dummyContext;
2019-06-18 01:53:54 +00:00
2019-04-12 14:37:47 +00:00
/**
2019-09-16 15:05:24 +00:00
* Returns the default system-wide [[Context]]
* @category Core
2019-04-12 14:37:47 +00:00
*/
export function getContext(): BaseContext {
2019-07-25 22:32:58 +00:00
if (globalContext === dummyContext && hasAudioContext) {
setContext(new Context());
2019-04-12 14:37:47 +00:00
}
return globalContext;
}
/**
* Set the default audio context
* @param context
* @param disposeOld Pass `true` if you don't need the old context to dispose it.
2019-09-16 15:05:24 +00:00
* @category Core
2019-04-12 14:37:47 +00:00
*/
export function setContext(context: BaseContext | AnyAudioContext, disposeOld = false): void {
if (disposeOld) {
globalContext.dispose();
}
if (isAudioContext(context)) {
globalContext = new Context(context);
} else if (isOfflineAudioContext(context)) {
globalContext = new OfflineContext(context);
} else {
globalContext = context;
}
2019-04-12 14:37:47 +00:00
}
/**
* Most browsers will not play _any_ audio until a user
* clicks something (like a play button). Invoke this method
* on a click or keypress event handler to start the audio context.
* More about the Autoplay policy
* [here](https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio)
* @example
2019-10-24 22:01:27 +00:00
* document.querySelector("button").addEventListener("click", async () => {
* await Tone.start();
* console.log("context started");
* });
2019-09-16 15:05:24 +00:00
* @category Core
2019-04-12 14:37:47 +00:00
*/
export function start(): Promise<void> {
return globalContext.resume();
2019-04-12 14:37:47 +00:00
}
/**
2019-05-23 18:00:49 +00:00
* Log Tone.js + version in the console.
2019-04-12 14:37:47 +00:00
*/
if (theWindow && !theWindow.TONE_SILENCE_LOGGING) {
2019-05-23 18:00:49 +00:00
let prefix = "v";
if (version === "dev") {
prefix = "";
}
const printString = ` * Tone.js ${prefix}${version} * `;
2019-09-14 22:12:44 +00:00
// eslint-disable-next-line no-console
2019-05-23 18:00:49 +00:00
console.log(`%c${printString}`, "background: #000; color: #fff");
}