Skip to content

Commit

Permalink
implement preload to the audio component
Browse files Browse the repository at this point in the history
  • Loading branch information
EvandroLG committed Nov 3, 2021
1 parent e187ecd commit cb517e3
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 2 deletions.
3 changes: 2 additions & 1 deletion demo/audio/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ const buttonPause = document.getElementById('bt-pause');
const buttonStop = document.getElementById('bt-stop');
const audio: AudioType = Audio({
file: song,
loop: false,
loop: true,
volume: getVolume(range),
preload: true,
});

audio.on('end', () => {
Expand Down
7 changes: 6 additions & 1 deletion src/audio/Audio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import EventHandler from '../EventHandler';
import initializeSource from './initializeSource';
import decodeAudioData from './decodeAudioData';
import { AudioPropType, AudioEventType, AudioType } from './types';
import { getBuffer } from '../utils';
import { getBuffer, preloadFiles } from '../utils';

// if audiocontext is initialized before a user gesture on the page, its
// state become `suspended` by default. once audiocontext.state is `suspended`
Expand All @@ -20,6 +20,7 @@ const Audio = ({
volume = 1,
autoPlay = false,
loop = false,
preload = false,
}: AudioPropType): AudioType => {
const audioCtx = AudioCtx();
const states = { ...globalStates };
Expand All @@ -43,6 +44,10 @@ const Audio = ({
.catch(console.error);
};

if (preload) {
preloadFiles([file], 1);
}

return {
play() {
if (states.hasStarted) {
Expand Down
1 change: 1 addition & 0 deletions src/audio/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export type AudioPropType = {
volume?: number;
autoPlay?: boolean;
loop?: boolean;
preload?: boolean;
};

export type AudioEventType = 'ready' | 'start' | 'state' | 'end';
Expand Down

0 comments on commit cb517e3

Please sign in to comment.