Using Javascript for background music audio

Jun 26, 2017

Hello all! I've searched the internet and the forum discussions but can't seem to find the answer to my problem. I have a javascript I'm using to cue the background music audio on slide 3 of my course. However I want to have the music stop playing if the user decides to go back to slide 2 to watch the video again. I tried using two  javascript's, one for a silent mp3 music track on slide 2, and then the same javascript for cueing up the background music on slide 3. Seems like they conflict with each other. Does anyone know of a solution for this? Help would be most appreciated. Thanks!

This is the js I'm currently using:

//load the scripts dynamically into the head of the document
function add_line() {
var line = document.createElement("audio");
var head=document.getElementsByTagName('body')[0];
line.type = "audio/mp3";
line.src="SpaceJazzEdit.mp3";
line.id="bgSong" ;
line.autoplay = true;
head.appendChild(line);
}

//but we only want to add these once!
if(document.getElementById('bgSong')==null){
add_line();
var audio = document.getElementById('bgSong');
audio.volume = 0.5;
}

 

7 Replies
Ashley Terwilliger-Pollard

Hi Robert,

The javascript element isn't something I can help with - but I know we've got a number of community members who have created a similar set up. You may want to reach out to folks in either of these discussions:

Hope that you find the help you need! 

Russell Killips

I would put the pause script on slide 2.

var audio = document.getElementById('bgSong');
audio.pause();

And then modify the script on slide 3 to:

//load the scripts dynamically into the head of the document
function add_line() {
var line = document.createElement("audio");
var head=document.getElementsByTagName('body')[0];
line.type = "audio/mp3";
line.src="SpaceJazzEdit.mp3";
line.id="bgSong" ;
line.autoplay = true;
head.appendChild(line);
}

//but we only want to add these once!
if(document.getElementById('bgSong')==null){
add_line();
var audio = document.getElementById('bgSong');
audio.volume = 0.5;
}else{
var audio = document.getElementById('bgSong');
audio.play();
}

Travis Thompson

Ardiannie - Looks like I'm about a year late answering your question, but yes you can do that by just assigning each song a different line id.  For example, instead of using "bgSong" for each audio file, use bgSong1, bgSong2, etc.  Just make sure you pause the first audio before playing the second using the code that Russell posted on his first response.

This discussion is closed. You can start a new discussion or contact Articulate Support.