Skip to main content

canPlay

Check whether this browser can play a format, by its extension. Use it to pick a file yourself, or to warn a user before a load that cannot work.

canPlay(format: string): boolean;

Parameters​

ParameterTypeDefaultDescription
formatstringrequiredA file extension such as 'opus' or '.mp3'. The leading dot is optional and case does not matter.

Returns​

boolean: true when the browser says it can play the format. false when it cannot, and for an extension soundhub does not know.

Example​

import { SoundHub } from 'soundhub';

// Static: works before a hub exists
SoundHub.canPlay('opus'); // false on older Safari
SoundHub.canPlay('.MP3'); // true

const soundHub = new SoundHub();
const url = soundHub.canPlay('opus') ? '/audio/theme.opus' : '/audio/theme.mp3';
await soundHub.loadSound('music', url);

Letting the library pick​

You rarely need to call this yourself. Hand loadSound a list of urls and it picks the first format the browser accepts, before anything is fetched:

await soundHub.loadSound('music', [
'/audio/theme.opus', // Chrome, Firefox, Edge
'/audio/theme.m4a', // Safari
]);

Good to know​

  • There is a static SoundHub.canPlay() as well as the instance method, so you can ask before you build a hub. Both give the same answer.
  • The answer comes from the browser's own canPlayType, and "maybe" counts as yes.
  • Known extensions: mp3, mpeg, opus, ogg, oga, wav, aac, caf, m4a, m4b, mp4, weba, webm, flac and dolby. Opus and Vorbis are asked for with their codec, because Safari says "maybe" to a bare audio/ogg and then fails to decode.
  • The answer is cached per extension. Without a document (server-side rendering) the answer is false.
  • Added in 6.2.0.

See also​