Reputation: 57
Following up my last question : Play a sound when a trigger word is shown
I incorporated the code and it works perfectly, until I generate more triggers and they all stack on on top of each other's. Also when a new trigger is shown in the page, the old trigger starts playing as well.
example:
CAT is shown ---> meow
DOG is show -----> meow + bark
but when bark plays I do not want meow to play as well. If it already played it should not play.
this is the audio part of my code where I generate the sound
var elements = document.querySelectorAll(".robotMessage");
for (let message of elements) {
const text = message.innerText;
for (let trigger of triggers) {
if (text.toLowerCase().indexOf(trigger.name.toLowerCase()) !== -1) {
const track = new Audio(trigger.sound);
track.load();
track.play();
track.volume = 0.5;
}
}
}
A part of my audio:
var triggers = [
{
name: "skating",
sound: "https://actions.google.com/sounds/v1/sports/skateboard_kick_push.ogg"
},
{
name: "rollerblading",
sound: "./sounds/Rollerblading.mp3"
},
{
name: "walk",
sound: "https://actions.google.com/sounds/v1/foley/walk.ogg"
},
{
name: "walking",
sound: "https://actions.google.com/sounds/v1/foley/walk.ogg"
}];
Is there a way to fix it? I've been researching for days but I cannot find a good solution to it. Is there a way to maybe go around it? Any help is appreciated.
Upvotes: 0
Views: 149
Reputation: 1568
I think the problem here is that you are reading all the triggers again, when you're supposed to read just the last one. Try this way:
when trigger is added:
var elements = document.querySelectorAll(".robotMessage");
var message = elements[elements.length-1]; //get last message
const text = message.innerText;
for (let trigger of triggers) {
if (text.toLowerCase().indexOf(trigger.name.toLowerCase()) !== -1) {
var track = new Audio(trigger.sound);
track.load();
track.play();
track.volume = 0.5;
}
}
Upvotes: 2