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
| Parameter | Type | Default | Description |
|---|---|---|---|
format | string | required | A 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,flacanddolby. Opus and Vorbis are asked for with their codec, because Safari says "maybe" to a bareaudio/oggand then fails to decode. - The answer is cached per extension. Without a
document(server-side rendering) the answer isfalse. - Added in 6.2.0.
See also
getSupportedFormats: every extension this browser accepts.loadSound: takes a list of urls and picks for you.getSoundUrls: the list a sound was given.