@4players/odin
Version:
A cross-platform SDK enabling developers to integrate real-time VoIP chat technology into their projects
64 lines (63 loc) • 2.5 kB
JavaScript
import { assert } from '@4players/odin-common';
export let PLUGIN;
export const SUPPORTED_API_VERSION = '9';
let pluginPromise;
/**
* Ensures a plugin is available for the SDK. If no plugin is provided, a default web plugin is created
* using `@4players/odin-plugin-web`.
*
* If the plugin is already registered, the existing plugin is returned immediately.
* If registration is in progress (e.g. from a concurrent call), the same pending promise is returned.
*
* @param {Plugin} [plugin] - An optional plugin instance. When omitted, a default web plugin is created automatically.
* @returns {Promise<Plugin>} A promise that resolves to the registered plugin.
*/
export function ensurePlugin(plugin) {
if (PLUGIN) {
return Promise.resolve(PLUGIN);
}
if (pluginPromise) {
return pluginPromise;
}
pluginPromise = (async () => {
try {
if (!plugin) {
const { createPlugin } = await import('@4players/odin-plugin-web');
plugin = createPlugin(async (sampleRate) => {
const audioContext = new AudioContext({ sampleRate });
await audioContext.resume();
return audioContext;
});
}
assert(plugin.version === SUPPORTED_API_VERSION, `Only plugins with version "${SUPPORTED_API_VERSION}" are supported.`);
PLUGIN = plugin;
return plugin;
}
catch (e) {
pluginPromise = undefined;
throw e;
}
})();
return pluginPromise;
}
/**
* Replaces the current plugin with a new one. Unlike {@link ensurePlugin}, this always overwrites
* the existing plugin, even if one is already registered.
*
* @param {Plugin} plugin - The plugin instance to use. Must match the supported API version.
*/
export function replacePlugin(plugin) {
assert(plugin.version === SUPPORTED_API_VERSION, `Only plugins with version "${SUPPORTED_API_VERSION}" are supported.`);
PLUGIN = plugin;
pluginPromise = Promise.resolve(plugin);
}
/**
* Sets the audio output device globally across all rooms.
*
* @param {Backend.DeviceParameters} [device={}] - The parameters of the audio output device to be set.
* @returns {Promise<void>} A promise that resolves when the audio output device has been successfully set.
*/
export async function setOutputDevice(device = {}) {
const plugin = await ensurePlugin();
await plugin.setOutputDevice(device);
}