An utility for playing sounds in Svelte using svelte actions
npm install svelte-sound   !Made for svelte
Svelte Actions to play interaction sounds on target DOM events
- Lightweight and performant
- Only Howler core is used
- Loads Howler using dynamic imports to support partial hydration
- Scalable (can be used in complex game interactions)
- Truly reactive by default
``sh`
npm i svelte-sound
or
`sh`
yarn add svelte-sound
or
`sh`
pnpm i svelte-sound
svelte-sound can be used in three ways,
1. sounduseSound
2. Sound
3. class
This can be directly used on elements within svelte as a svelte action.
This actions following mandatory options,
| Option | Type | Description |
| --- | --- | --- |
| src | string | The source of the sound file |events
| | [PlayEvent, StopEvent?] | An array of events to play and stop the sound |
and valid Howler Core Options as optional options
`svelte
`
This can be reused multiple times on multiple elements within svelte. This returns a svelte action.
This method accepts following parameters,
| Parameter | Type | Description |
| --- | --- | --- |
| src | string | The source of the sound file |events
| | [PlayEvent, StopEvent?] | An array of events to play and stop the sound |options
| | HowlerOptions? | An object of valid Howler Core Options |
`svelte
`
This can be used to play the sound programmatically. This returns a Sound class instance.src
This method accepts following parameters,
| Parameter | Type | Description |
| --- | --- | --- |
| | string | The source of the sound file |options
| | HowlerOptions? | An object of valid Howler Core Options |
`js
import { Sound } from "svelte-sound";
import click_mp4 from "./assets/click.mp4";
const click_sound = new Sound(click_mp4);
function playSound() {
click_sound.play();
} // playSound can be called anywhere in the code
`
For usage example have a look at example directory
> How to Stop the sound/audio?
You can always pass an event as the second element of the events array to stop the sound on that event.
e.g.
`svelte
`
In the above example the sound will be played on click and stopped on dblclick
Alternatively you can use play and stop methods added to the element by the action. To play or stop the sound you can call the respective methods on the element.
e.g.
`svelte
bind:this={button}
on:dblclick={() => button.stop()}
use:sound={{src: click_mp4, events: ["click"]}}>
Click Me!!
`
In the above example the sound will be played on click and stopped on dblclick using the stop method which we done programmatically.
> How to use this library programmatically without any DOM events?
You can use Sound class exported by the package to play the sound programmatically.
e.g.
`js
import { Sound } from "svelte-sound";
import click_mp4 from "./assets/click.mp4";
const click_sound = new Sound(click_mp4);
function playSound() {
click_sound.play();
}
`play
In the above example the sound will be played on calling the method of the click_sound object.