Rob Colbert
2 years ago
5 changed files with 30 additions and 120 deletions
@ -1,89 +0,0 @@ |
|||
// lib/game-voice-channels.js
|
|||
// Copyright (C) 2022 Rob Colbert @[email protected]
|
|||
// License: Apache-2.0
|
|||
|
|||
'use strict'; |
|||
|
|||
import { NiceLog } from "dtp-nice-game"; |
|||
|
|||
export class VoiceChannel { |
|||
|
|||
constructor (game, name) { |
|||
this.game = game; |
|||
this.name = name; |
|||
|
|||
this.log = new NiceLog(`VoiceChannel:${name}`); |
|||
this.log.enable(); |
|||
|
|||
this.playing = false; |
|||
|
|||
this.quips = [ ]; |
|||
} |
|||
|
|||
async loadQuip (soundId) { |
|||
if (this.quips.includes(soundId)) { |
|||
throw new Error(`Quip ${soundId} has already been loaded`); |
|||
} |
|||
this.quips.push(soundId); |
|||
return this.game.audio.loadSound(soundId, `/dist/assets/audio/vox/${soundId}.wav`); |
|||
} |
|||
|
|||
playRandomQuip ( ) { |
|||
this.log.debug('playRandomQuip', 'request to play random quipt', { playing: this.playing }); |
|||
if (this.playing) { |
|||
return; |
|||
} |
|||
|
|||
const soundId = this.getRandomQuipSoundId(); |
|||
this.log.debug('playRandomQuip', 'playing random voiceover sound', { soundId }); |
|||
const { source } = this.game.audio.playSound(soundId); |
|||
source.addEventListener('ended', ( ) => { |
|||
this.log.debug('playRandomQuip', 'quip ending', { soundId }); |
|||
this.playing = false; |
|||
}); |
|||
|
|||
this.playing = true; |
|||
} |
|||
|
|||
getRandomQuipSoundId ( ) { |
|||
if (!Array.isArray(this.quips) || (this.quips.length === 0)) { |
|||
throw new Error(`No valid quips loaded on channel "${this.name}"`); |
|||
} |
|||
const quipIdx = Math.floor(Math.random() * (this.quips.length - 1)); |
|||
const quipSoundId = this.quips[quipIdx]; |
|||
this.log.debug('getRandomQuipSoundId', 'selected a random quip', { quipIdx, quipSoundId }); |
|||
return quipSoundId; |
|||
} |
|||
} |
|||
|
|||
/** |
|||
* GameVoiceChannels tracks audio playing in named channels and will prevent the |
|||
* game from playing a sound on a channel if a sound is currently playing on |
|||
* that channel. |
|||
*/ |
|||
export class GameVoiceChannels { |
|||
|
|||
constructor (game) { |
|||
this.game = game; |
|||
this.channels = { }; |
|||
} |
|||
|
|||
addChannel (channelName) { |
|||
const channel = new VoiceChannel(this.game, channelName); |
|||
this.channels[channelName] = channel; |
|||
return channel; |
|||
} |
|||
|
|||
getChannel (channelName) { |
|||
const channel = this.channels[channelName]; |
|||
if (!channel) { |
|||
throw new Error(`Invalid voice channel "${channelName}"`); |
|||
} |
|||
return channel; |
|||
} |
|||
|
|||
playSound (channelName, soundId) { |
|||
const channel = this.getChannel(channelName); |
|||
channel.playSound(soundId); |
|||
} |
|||
} |
Loading…
Reference in new issue