API | Audio

These functions control the playback of audio files.

 

PS.audioLoad ( filename, options )

PS.audioLoad() preloads an audio file, allocates a channel ID to the loaded audio, and optionally plays it.

Parameters:

  1. filename : string
  2. (optional) options : object or PS.DEFAULT

Returns: PS.DONE or PS.ERROR

The filename parameter should be a case-sensitive string matching the filename of the audio to be played, without a path specifier or file extension (example: "fx_click"). By default, the file is assumed to reside in the Perlenspiel Audio Library. Note that library filenames are all lower-case.

If filename is specified as an empty string (""), PS.audioLoad() has no effect, and immediately returns the value PS.DONE.

The options parameter, if provided, should be a JavaScript object containing one or more of the following case-sensitive properties:

options.autoplay

If options.autoplay is true or a non-zero number, the audio file specified by filename is played immediately upon loading. Any playback behaviors specified by other parameters in the options object (such as .volume and .loop) will be applied.

If options.autoplay is false, zero (0), null, PS.DEFAULT or not supplied, the default behavior (no autoplay) is applied.

options.volume

The options.volume property specifies the volume assigned to subsequent playback of the audio file specified by filename. It should be expressed as a float in the range 0 (muted) to 1.0 (maximum) inclusive. Values outside this range are clamped.

If options.volume is null, PS.DEFAULT or not supplied, the default volume (0.5, 50% maximum) is applied.

options.loop

If options.loop is true or a non-zero number, the audio file specified by filename will loops continuously on subsequent playback. If options.loop is false, zero (0), null, PS.DEFAULT or not supplied, the default behavior (no looping) is applied.

options.lock

If options.lock is true or a non-zero number, the audio file specified by filename is marked for long-term retention by the audio engine. Such files are less likely to be discarded if the engine needs more space. If options.lock is false, zero (0), null, PS.DEFAULT or not supplied, the default behavior (no file lock) is applied.

options.onLoad

The options.onLoad property specifies a JavaScript function that will be called when the audio file specified by filename is completely loaded, and a channel has been successfully allocated to it. It should be a reference to a valid JavaScript function expecting one parameter, which will be an object containing the following case-sensitive properties:

If options.onLoad is null, PS.DEFAULT or not supplied, no function will be called upon completion of file loading.

options.onEnd

The options.onEnd property specifies a JavaScript function that will be called each time the audio channel (not the file!) allocated by this call to PS.audioLoad() completes playback, including the end of each loop, if looping is enabled on the channel. It should be a reference to a valid JavaScript function expecting one parameter, which will be an object containing the same case-sensitive properties as those sent to the options.onLoad function (see above).

If options.onEnd is null, PS.DEFAULT or not supplied, no function will be called upon completion of channel playback.

options.data

If an .onLoad or .onEnd property is provided in the options object, the options.data property specifies the value that will be assigned to the .data property of the object passed to those functions when they are called. Any valid JavaScript value can be specified.

If the options.data property is null, PS.DEFAULT or not supplied, the filename parameter passed to PS.audioLoad() will be assigned to the .data property of the object passed to those functions.

options.path

The options.path property is used to specify the location of custom audio files not sourced from the Perlenspiel Audio Library. It should be a case-senstive string representing the path to the directory containing the audio file(s) specified by the filename parameter, relative to the directory containing the project's game.html file.

For example, suppose you have placed your custom sound files in a subdirectory named audio, located in the same directory as your game.html file, like this:

game.html
game.js
audio/
 mysound.ogg
 mysound.mp3

In this case, you would specify the string "audio/" in the options.path property.

To play audio files located in the same directory as the game.html file, specify the string "./" in the options.path property.

If options.path is an empty string (""), null, PS.DEFAULT or not supplied, the path of the Perlenspiel Audio Library is applied.

IMPORTANT: Webkit-based browsers, such as Chrome, Edge and Brave, are picky about security. By default, they will not load resources (including custom audio and image files) that (1) do not reside on an actual HTTP or HTTPS server, and (2) do not share the root filepath of any script that tries to access them. This means that you have to install all of your scripts, audio and image files on a live server, in the same root filepath, before you can test or deploy an application using these browsers. (It's possible to reconfigure browsers to avoid this necessity, but this is not recommended.)

Firefox is currently more lenient about security. Resource files don't need to be on a server, or share the same root filepath. This leniency is subject to change at any time.

options.fileTypes

The options.fileTypes property is used to specify which file formats are available for any custom audio files used by your project. This property should be an array of lower-case strings indicating the filetypes provided for the file specified by the filepath parameter. The strings should be provided in priority order; compressed formats (such as .mp3 and .ogg) should appear first. Legal strings are:

Note that filetype specifiers should not be prefixed by a period (".ogg").

Preparing custom audio files

All major browsers can play either .ogg or .mp3 files, but not necessarily both. For maximum compatibility, you should provide both .ogg and .mp3 versions of every custom sound you want to use. All files must be stored in the same directory. Both versions of each sound file should share exactly the same case-sensitive filename, suffixed with a format-appropriate lower-case extension (.ogg or .mp3). Perlenspiel will automatically detect and play the file version compatible with your browser.

Encode the compressed formats at whatever bitrate you feel is adequate. For stereo music, I recommend at least 160 kbps for .mp3 files, and 128 kbps for .ogg files. Lower bitrates may be adequate for voices, sound effects and/or or monaural sounds.

For future compatibility, you may also want to provide a 44.1kHz .webm file (Opus codec preferred, Vorbis format acceptable). Opus-encoded .webm files sound noticeably better than .ogg or .mp3 files encoded at the same bitrate. The .webm format is already supported by many major browsers, and is now part of the official HTML5 standard, which means it will eventually become compatible with all browsers.

If options.fileTypes is PS.DEFAULT or not supplied, the default fileTypes array for the browser running Perlenspiel is applied. This will usually (but not necessarily) be:

If the options parameter of PS.audioLoad() is PS.DEFAULT or not supplied, default values are used for all of the above properties.

Return value

PS.audioLoad() returns the constant PS.DONE on successful completion, or if an empty string was passed to its filename parameter.

PS.ERROR is returned if an error occurs.

// EXAMPLE:
// Preload and lock a library sound on startup,
// and save its channel ID for future use.

var click_id = ""; // variable to save channel ID

PS.init = function( system, options ) {
 // set up a 10 x 10 grid

 PS.gridSize( 10, 10 );

 // Loader function to save channel ID

 var loader = function ( data ) {
 click_id = data.channel; // save ID
 };

 // Load the sound

 PS.audioLoad( "fx_click", {
 lock : true,
 onLoad : loader // specify loader function
 } );
};

 

PS.audioPlay ( filename, options )

PS.audioPlay() plays an audio file, automatically loading it and allocating a channel to it first if necessary. It works exactly the same way PS.audioLoad() operates when the .autoplay property of its options parameter is set to true.

Parameters:

  1. filename : string
  2. (optional) options : object or PS.DEFAULT

Returns: PS.DONE or PS.ERROR

The filename parameter should be a case-sensitive string matching the filename of the audio to be played, without a file extension. By default, the file is assumed to reside in the Perlenspiel Audio Library. Note that library filenames are all lower-case.

If filename is specified as an empty string (""), PS.audioPlay() has no effect, and immediately returns the value PS.DONE.

The options parameter, if provided, should by a JavaScript object containing one or more of the following case-sensitive properties:

See the documentation for PS.audioLoad() above for a detailed description of these properties.

If options is PS.DEFAULT or not supplied, default values are used for all properties.

Return value

PS.audioPlay() returns the constant PS.DONE on successful completion, or if an empty string was passed to its filename parameter.

PS.ERROR is returned if an error occurs.

// EXAMPLES:

// Play a pop when any bead is clicked/touched

PS.touch = function( x, y, data, options ) {
 PS.audioPlay( "fx_pop" );
};

// Play triangle at 75% volume
// when any key is pressed

PS.keyDown = function( key, shift, ctrl, options ) {
 PS.audioPlay( "perc_triangle", { volume: 0.75 } );
};

 

PS.audioPlayChannel ( channel, options )

PS.audioPlayChannel() plays an audio channel previously allocated by a call to PS.audioLoad() or PS.audioPlay().

Parameters:

  1. channel : string
  2. (optional) options : object or PS.DEFAULT

Returns: string or PS.ERROR

The channel parameter should be a channel ID string previously allocated by a call to PS.audioLoad() or PS.audioPlay().

Playback of channel always starts at the beginning of the asscoaited audio file.

If PS.audioPlayChannel() is called when the specified channel is already playing as the result of a previous call, the first playback instance will immediately stop, and the channel will start playing again from the beginning.

If channel is specified as an empty string (""), PS.audioPlayChannel() has no effect, and immediately returns the constant PS.DONE.

An error occurs if the channel parameter is invalid.

The options parameter, if provided, should by a JavaScript object containing one or more of the following properties:

See the documentation for PS.audioLoad() above for a detailed description of these properties. NOTE: Only the four properties listed above apply to PS.audioPlayChannel().

If options is PS.DEFAULT or not supplied, default values are used for all properties.

Return value

PS.audioPlayChannel() returns its channel parameter upon successful completion, or the constant PS.DONE if an empty string is passed to its channel parameter.

PS.ERROR is returned if an error occurs.

// EXAMPLE:

var pop_id = ""; // variable to save channel ID

// Preload and lock a library sound on startup,
// and save its channel ID for future use.

PS.init = function( system, options ) {
 // set up a 10 x 10 grid

 PS.gridSize( 10, 10 );

 // Loader function to save channel ID

 var loader = function ( data ) {
 pop_id = data.channel; // save ID
 };

 // Load the sound

 PS.audioLoad( "fx_pop", {
 lock : true,
 onLoad : loader // specify loader function
 } );
};

// Play a pop when any bead is clicked/touched

PS.touch = function( x, y, data, options ) {
 PS.audioPlayChannel ( pop_id );
};

 

PS.audioFade ( channel, from, to, duration, onEnd )

PS.audioFade() lets you linearly fade a currently playing audio channel up or down.

Parameters:

  1. channel : string
  2. from : number or PS.CURRENT
  3. to : number
  4. (optional) duration : number or PS.DEFAULT
  5. (optional) onEnd : function or PS.DEFAULT

Returns: string, PS.DONE or PS.ERROR

The required channel parameter should be a channel ID string previously allocated by a call to PS.audioLoad() or PS.audioPlay().

If the audio channel specified by channel is currently playing when PS.audioFade() is called, the fade effect specified by its remaining parameters begins immediately.

If channel is not currently playing when PS.audioFade() is called, or if channel is specified as an empty string (""), PS.audioFade() has no effect, and immediately returns the constant PS.DONE.

An error occurs if the channel parameter is invalid.

The required from parameter specifies the audio level from which the fade effect will begin. It should be a float between 0 (silence) and 1 (full volume). Values outside this range are clamped. If from is specified as PS.CURRENT, the fade effect begins at the channel's current volume level.

The required to parameter specifies the audio level at which the fade effect will end. It should be a float between 0 (silence) and 1 (full volume). Values outside this range are clamped. An error occurs if the values of from and to are specified identically.

The optional duration parameter specifies the duration of the fade effect in milliseconds. It should be a integer greater than or equal to 1. Non-integral numbers are floored. Values less than 1 will cause an error. If duration is specified as PS.DEFAULT or not supplied, the default duration value (1000, one second) is used for the fade effect.

The optional onEnd parameter specifies a function that will be called when the fade effect is complete. It should be a valid JavaScript function expecting a single parameter, which will be passed the string specified by the channel parameter. If onEnd is specified as PS.DEFAULT or not supplied, no function is called when the fade effect is complete.

If PS.audioPause() or PS.audioStop() is called on a channel currently being faded, the fade effect is immediately cancelled. If an onEnd function was specified for the cancelled fade effect, that function is immediately called when the fading channel is paused or stopped.

Return value

PS.audioFade() returns its channel parameter upon successful completion, or the constant PS.DONE if an empty string is passed to its channel parameter.

PS.ERROR is returned if an error occurs.

 

PS.audioPause ( channel )

PS.audioPause() lets you pause and/or resume a previously played audio channel.

Parameters:

  1. channel : string

Returns: string or PS.ERROR

The channel parameter should be a channel ID string previously allocated by a call to PS.audioLoad() or PS.audioPlay().

If the audio channel specified by channel is playing, it will pause immediately. If channel is already paused as a result of a previous call to PS.audioPause(), it resumes playing at the point from which it was paused.

If channel is not playing or previously paused, nothing happens.

If channel is specified as an empty string (""), PS.audioPause() has no effect, and immediately returns the constant PS.DONE.

An error occurs if the channel parameter is invalid.

Return value

PS.audioPause() returns its channel parameter upon successful completion, or the constant PS.DONE if an empty string is passed to its channel parameter.

PS.ERROR is returned if an error occurs.

 

PS.audioStop ( channel )

PS.audioStop() lets you stop a previously started audio channel.

Parameters:

  1. channel : string

Returns: string or PS.ERROR

The channel parameter should be a channel ID string previously allocated by a call to PS.audioLoad() or PS.audioPlay().

If the audio channel specified by channel is playing, it stops immediately.

If channel is not playing, or was previously stopped, nothing happens.

If channel is currently paused by a previous call to PS.audioPause(), the pause is cancelled, and the location pointer of channel is reset to the beginning of the associated audio file. Subsequent calls to PS.audioPause() on channel will have no effect unless the channel is restarted by a call to PS.audioPlayChannel().

If channel is specified as an empty string (""), PS.audioStop() has no effect, and immediately returns the constant PS.DONE.

An error occurs if the channel parameter is invalid.

Return value

PS.audioStop() returns its channel parameter upon successful completion, or the constant PS.DONE if an empty string is passed to its channel parameter.

PS.ERROR is returned if an error occurs.

 

PS.piano ( note, long )

PS.piano() returns the filename of an indexed piano note.

Parameters:

  1. note : integer
  2. (optional) long : boolean

Returns: string or PS.ERROR

The Perlenspiel Audio Library includes a piano with 88 keys, ranging from A0 to C8 inclusive.

PS.piano() takes a note parameter between 1 and 88 inclusive, and returns a string representing the filename of the associated piano sound. Values outside this range are clamped.

There are two versions of each piano note, short (about 1 second in duration) and long (about 4 seconds). The optional long parameter determines which version's filename is returned. If long is true, the long version is returned. If long is false or not supplied, the short version is returned.

Return value

PS.piano() returns a string representing the filename of the piano sound specified by note and long.

PS.ERROR is returned if an error occurs.

// EXAMPLES:

// Play SHORT version of piano note 44
// when any bead is clicked/touched

PS.touch = function( x, y, data, options ) {
 PS.audioPlay( PS.piano( 44 ) );
};

// Play LONG version of piano note 32
// when any key is pressed

PS.keyDown = function( key, shift, ctrl, options ) {
 PS.audioPlay( PS.piano( 32, true ) );
};

 

PS.harpsichord ( note, long )

PS.harpsichord() returns the filename of an indexed harpsichord note.

Parameters:

  1. note : integer
  2. (optional) long : boolean

Returns: string or PS.ERROR

The Perlenspiel Audio Library includes a harpsichord with 57 keys, ranging from A2 to F7 inclusive.

PS.harpsichord() takes a note parameter between 1 and 57 inclusive, and returns a string representing the filename of the associated harpsichord sound. Values outside this range are clamped.

There are two versions of each harpsichord note, short (about 1 second in duration) and long (about 4 seconds). The optional long parameter determines which version's filename is returned. If long is true, the long version is returned. If long is false or not supplied, the short version is returned.

Return value

PS.harpsichord() returns a string representing the filename of the harpsichord sound specified by note and long.

PS.ERROR is returned if an error occurs.

 

PS.xylophone ( note )

PS.xylophone() returns the filename of an indexed xylophone note.

Parameters:

  1. note : integer

Returns: string or PS.ERROR

The Perlenspiel Audio Library includes a xylophone with 39 notes, ranging from A4 to B7 inclusive.

PS.xylophone() takes a note parameter between 1 and 39 inclusive, and returns a string representing the filename of the associated xylophone sound. Values outside this range are clamped.

Return value

PS.xylophone() returns a string representing the filename of the xylophone sound specified by note.

PS.ERROR is returned if an error occurs.

 

Audio library

The Perlenspiel audio library contains nearly 400 sounds that you can use in your games, including a full range of piano, harpsichord and xylophone notes, dozens of percussion instruments, and sound effects ranging from simple to silly.

To use these sounds, pass the filenames below as a string to the PS.audioLoad() and PS.audioPlay() commands. Be sure the filename is spelled correctly! Note that filenames are all lower-case.

// EXAMPLE:
// Play a click when a bead is clicked

PS.touch = function ( x, y, data, options ) {
 PS.audioPlay( "fx_click" );
};

Click on any filename to hear what it sounds like.

Sound effects

All sound effect filenames begin with an fx_ prefix.

Percussion instruments

All percussion filenames begin with a perc_ prefix.

Piano notes

All 88 keys on a standard concert piano (notes A0 to C8) are available in two versions, short (about 1 second) and long (about 4 seconds).

You can translate a note number (1-88) to its associated filename with the PS.piano() function.

Short version filenames begin with a piano_ prefix.

Long version filenames begin with a l_piano_ prefix.

Harpsichord notes

A 57-key harpsichord manual (notes A2 to F7) is available in two versions, short (about 1 second) and long (about 4 seconds).

You can translate a harpsichord note number (1-57) to its associated filename with the PS.harpsichord() function.

Short version filenames begin with a hchord_ prefix.

Long version filenames begin with a l_hchord_ prefix.

Xylophone notes

Taps on a 39-note xylophone (notes A4 to B7) are available. Each begins with a xylo_ prefix.

You can translate a xylophone note number (1-39) to its associated filename with the PS.xylophone() function.