I have a sound player for notifications on my web application. I am using CakePHP as the backend and webpack for the front end. I am trying to create a class file that will first get the current user's sound preferences when the object is instantiated and then a method within the Sound class.
I first start with an axios call in the constructor. My assumption is that the constructor would wait for the axios call to finish before actually doing anything. But when I run something like:
const sound = new Sound();
sound.playTone(Sound.MESSAGE);
All I get is an issue with trying to insert the promise into the the path for the server to play the sound. I am at day 2 of trying to figure this out and have tried to use async and await to run the playTone() and it still is not working properly.
IMPORTANT: I am trying to eventually make it so that the application can have the preferences loaded up all at once so that the same object can be instantiated once and then play the tones needed, because there are multiple tones you can see. I don't want to have to ask the server every time what the tone is because of bandwidth issues that might start to creep up.
"use strict";
import axios from "axios";
/**
* Sounds class
*/
export class Sound
{
/**
* Message flag
*
* @type {string}
*/
static MESSAGE = 'message';
/**
* Email flag
*
* @type {string}
*/
static EMAIL = 'email';
/**
* Error flag
*
* @type {string}
*/
static ERROR = 'error';
/**
* Class constructor
*/
constructor()
{
axios.get('/preferences/get-message-preference')
.then(response => {
this._messagePath = response.data.value;
})
.catch(err => {
this._messagePath = 'tweet-416';
console.error(`Could not get preference: ${err}`)
})
.finally(() => {
console.log(`Test completed: ${this.messagePath}`)
})
}
get messagePath()
{
return this._messagePath;
}
/**
* Play Alert Tone
*
* Play a tone in the client to indicate something the user should direct heir attention to.
* Use sparingly!
*
* @param {string} type Classification of the tone that should be played.
* @return {Promise<void>} Promise is also caught in the method.
*/
playTone = (type) => {
return new Audio(`/material/fx/${this.#getPath(type)}.mp3`)
.play()
.catch(error => {
if (error.name === 'NotAllowedError')
console.warn('Could not play sound. Interaction requirements not met');
else console.error(`Could not play sound: ${error.name}`);
});
}
/**
* Get Tone File Path
*
* Get the relative/web path for the sound tone file.
*
* @param {string} type The classification of the tone.
* @return {string} Relative/web path for the sound tone file specified.
*/
#getPath = (type) => {
switch (type) {
case Sound.MESSAGE:
return this.messagePath;
case Sound.EMAIL:
case 'your-turn-491':
return 'your-turn-491';
case Sound.ERROR:
case 'long-expected-548':
return 'long-expected-548';
case 'Pop-Tone':
default:
return 'Pop-Tone';
}
}
}