# SoundInstance

Class · extends [`EventHandler`](https://api.playcanvas.com/engine/classes/EventHandler.md) · category: Sound

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/sound/instance.js#L47

A SoundInstance plays a [Sound](https://api.playcanvas.com/engine/classes/Sound.md).

One instance is one playback. It wraps an `AudioBufferSourceNode`, available as [source](https://api.playcanvas.com/engine/classes/SoundInstance.md#source)
once playing, with a gain for [volume](https://api.playcanvas.com/engine/classes/SoundInstance.md#volume), and carries [pitch](https://api.playcanvas.com/engine/classes/SoundInstance.md#pitch), [loop](https://api.playcanvas.com/engine/classes/SoundInstance.md#loop),
[startTime](https://api.playcanvas.com/engine/classes/SoundInstance.md#starttime) and [duration](https://api.playcanvas.com/engine/classes/SoundInstance.md#duration) to select the region of the sound it plays. [play](https://api.playcanvas.com/engine/classes/SoundInstance.md#play),
[pause](https://api.playcanvas.com/engine/classes/SoundInstance.md#pause), [resume](https://api.playcanvas.com/engine/classes/SoundInstance.md#resume) and [stop](https://api.playcanvas.com/engine/classes/SoundInstance.md#stop) drive it and fire the events of the same names,
with `end` fired when playback finishes on its own; [isPlaying](https://api.playcanvas.com/engine/classes/SoundInstance.md#isplaying), [isPaused](https://api.playcanvas.com/engine/classes/SoundInstance.md#ispaused) and
[isStopped](https://api.playcanvas.com/engine/classes/SoundInstance.md#isstopped) report the state, and [currentTime](https://api.playcanvas.com/engine/classes/SoundInstance.md#currenttime) can be read or set to seek.
Instances are normally created by [SoundSlot#play](https://api.playcanvas.com/engine/classes/SoundSlot.md#play) on a [SoundComponent](https://api.playcanvas.com/engine/classes/SoundComponent.md), which
returns the instance so a script can adjust or stop that one playback. [setExternalNodes](https://api.playcanvas.com/engine/classes/SoundInstance.md#setexternalnodes)
inserts Web Audio nodes such as filters between the source and the destination.

**Example**

```ts
const instance = entity.sound.play('engine');
instance.pitch = 1.5;
instance.once('end', () => console.log('finished'));
```

## Constructors

### constructor

```ts
new SoundInstance(manager: SoundManager, sound: Sound, options: object)
```

Create a new SoundInstance instance.

**Parameters**

- `manager` ([`SoundManager`](https://api.playcanvas.com/engine/classes/SoundManager.md)): The sound manager.
- `sound` ([`Sound`](https://api.playcanvas.com/engine/classes/Sound.md)): The sound to play.
- `options` (`object`): Options for the instance.
    - `options.duration` (`number`, optional): The total time after the startTime in seconds when
      playback will stop or restart if loop is true. Defaults to 0.
    - `options.loop` (`boolean`, optional): Whether the sound should loop when it reaches the end or
      not. Defaults to false.
    - `options.onEnd` (`Function`, optional): Function called when the instance ends.
    - `options.onPause` (`Function`, optional): Function called when the instance is paused.
    - `options.onPlay` (`Function`, optional): Function called when the instance starts playing.
    - `options.onResume` (`Function`, optional): Function called when the instance is resumed.
    - `options.onStop` (`Function`, optional): Function called when the instance is stopped.
    - `options.pitch` (`number`, optional): The relative pitch. Defaults to 1 (plays at normal pitch).
    - `options.startTime` (`number`, optional): The time from which the playback will start in
      seconds. Default is 0 to start at the beginning. Defaults to 0.
    - `options.volume` (`number`, optional): The playback volume, between 0 and 1. Defaults to 1.

## Properties

### source

```ts
source: AudioBufferSourceNode | null = null
```

Gets the source that plays the sound resource. Source is only available after calling play.

## Accessors

### currentTime

```ts
get currentTime(): number
set currentTime(value: number)
```

Gets the current time of the sound that is playing, relative to [startTime](https://api.playcanvas.com/engine/classes/SoundInstance.md#starttime).

### duration

```ts
get duration(): number
set duration(value: number)
```

Gets the duration of the sound that the instance will play starting from [startTime](https://api.playcanvas.com/engine/classes/SoundInstance.md#starttime).
The returned value is clamped to the time available after the normalized start time.

### isPaused

```ts
get isPaused(): boolean
```

Gets whether the instance is currently paused.

### isPlaying

```ts
get isPlaying(): boolean
```

Gets whether the instance is currently playing.

### isStopped

```ts
get isStopped(): boolean
```

Gets whether the instance is currently stopped.

### isSuspended

```ts
get isSuspended(): boolean
```

Gets whether the instance is currently suspended because the window is not focused.

### loop

```ts
get loop(): boolean
set loop(value: boolean)
```

Gets whether the instance will restart when it finishes playing.

### pitch

```ts
get pitch(): number
set pitch(pitch: number)
```

Gets the pitch modifier to play the sound with.

### sound

```ts
get sound(): Sound
set sound(value: Sound)
```

Gets the sound resource that the instance will play.

### startTime

```ts
get startTime(): number
set startTime(value: number)
```

Gets the start time from which the sound will start playing.

### volume

```ts
get volume(): number
set volume(volume: number)
```

Gets the volume modifier to play the sound with. In range 0-1.

## Methods

### clearExternalNodes

```ts
clearExternalNodes(): void
```

Clears any external nodes set by [setExternalNodes](https://api.playcanvas.com/engine/classes/SoundInstance.md#setexternalnodes).

### getExternalNodes

```ts
getExternalNodes(): AudioNode[]
```

Gets any external nodes set by [setExternalNodes](https://api.playcanvas.com/engine/classes/SoundInstance.md#setexternalnodes).

**Returns** `AudioNode[]`: Returns an array that contains the two nodes set by
[setExternalNodes](https://api.playcanvas.com/engine/classes/SoundInstance.md#setexternalnodes).

### pause

```ts
pause(): boolean
```

Pauses playback of sound. Call resume() to resume playback from the same position.

**Returns** `boolean`: Returns true if the sound was paused.

### play

```ts
play(): boolean
```

Attempt to begin playback the sound.
If the AudioContext is suspended, the audio will only start once it's resumed.
If the sound is already playing, this will restart the sound.

**Returns** `boolean`: True if the sound was started immediately.

### resume

```ts
resume(): boolean
```

Resumes playback of the sound. Playback resumes at the point that the audio was paused.

**Returns** `boolean`: Returns true if the sound was resumed.

### setExternalNodes

```ts
setExternalNodes(firstNode: AudioNode, lastNode?: AudioNode): void
```

Connects external Web Audio API nodes. You need to pass the first node of the node graph
that you created externally and the last node of that graph. The first node will be
connected to the audio source and the last node will be connected to the destination of the
AudioContext (e.g. speakers). Requires Web Audio API support.

**Parameters**

- `firstNode` (`AudioNode`): The first node that will be connected to the audio source of sound instances.
- `lastNode` (`AudioNode`, optional): The last node that will be connected to the destination of the AudioContext.
  If unspecified then the firstNode will be connected to the destination instead.

**Example**

```ts
const context = app.systems.sound.context;
const analyzer = context.createAnalyzer();
const distortion = context.createWaveShaper();
const filter = context.createBiquadFilter();
analyzer.connect(distortion);
distortion.connect(filter);
instance.setExternalNodes(analyzer, filter);
```

### stop

```ts
stop(): boolean
```

Stops playback of sound. Calling play() again will restart playback from the beginning of
the sound.

**Returns** `boolean`: Returns true if the sound was stopped.

## Events

### EVENT_END

```ts
static EVENT_END: string = 'end'
```

Fired when the sound currently played by the instance ends.

**Example**

```ts
instance.on('end', () => {
    console.log('Instance ended');
});
```

### EVENT_PAUSE

```ts
static EVENT_PAUSE: string = 'pause'
```

Fired when the instance is paused.

**Example**

```ts
instance.on('pause', () => {
    console.log('Instance paused');
});
```

### EVENT_PLAY

```ts
static EVENT_PLAY: string = 'play'
```

Fired when the instance starts playing its source.

**Example**

```ts
instance.on('play', () => {
    console.log('Instance started playing');
});
```

### EVENT_RESUME

```ts
static EVENT_RESUME: string = 'resume'
```

Fired when the instance is resumed.

**Example**

```ts
instance.on('resume', () => {
    console.log('Instance resumed');
});
```

### EVENT_STOP

```ts
static EVENT_STOP: string = 'stop'
```

Fired when the instance is stopped.

**Example**

```ts
instance.on('stop', () => {
    console.log('Instance stopped');
});
```

## Inherited from [EventHandler](https://api.playcanvas.com/engine/classes/EventHandler.md)

- `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler`
- `hasEvent(name: string): boolean`
- `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler`
- `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle`
- `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle`
