So I have a function like this:
function music(song) {
var audio = new Audio("audio/" + song + ".ogg");
audio.play();
}
And the problem I'm having is that audio.play() works perfectly, but if I try audio.pause() later (after defining the same variable), it doesn't work. However, if I do this:
function music() {
var audio = document.getElementById("songname");
audio.play();
}
Then I can define the variable and later use audio.pause() to pause the track. The problem is that I want to do this within javascript because I have a lot of tracks and I don't want to create audio elements for each one.
Why doesn't the first piece of code allow me to pause the audio later? Is there any way I can let it pause the audio later? If not, are there any alternatives that involve playing the audio from javascript by passing a parameter which is the song title? I don't want to have to include the src in the html.
I suspect that jQuery might have an easy solution for this but form what I've researched I couldn't find anything.
audio only exists inside the function. if you need access to it outside the function then return the instance of the Audio object you are creating:
function getAudio(song, play) {
var audio = new Audio("audio/" + song + ".ogg");
if(play) {
audio.play();
}
return audio;
}
var theTrack = getAudio('my_song', true);
theTrack.pause(); // pause the song
theTrack.play(); // play the song
The second example refers to what i assume is an audio element which in turn exposes the functionality of the Audio object. The reason the second function works anywhere is because the DOM element is always present in the DOM and you are referencing that to get at the underlying Audio API, as opposed to a using the Audio object/API directly.
I just tested a snippet and it works as such
function music(song) {
var audio = new Audio("audio/" + song + ".ogg");
audio.play();
setTimeout(function() { audio.pause(); }, 5000);
}
You can create the audio variable before defining the function.
var audio = new Audio();
function playMusic(song) {
audio.src = "audio/" + song + ".ogg";
audio.play();
}
function pauseMusic() {
audio.pause();
}
Related
I am trying to make a sound play when a button is clicked. Here is the function that I am trying to use:
function sound(){
var audio = new Audio("button.wav");
audio.play();
}
and then I have this at the bottom of the file:
document.getElementById("convert").onclick = function() { sound(); };
I know that the code works because if I put the 2 lines of code inside the sound function inside of another function that performs a calculation on the button click, the sound plays. Why is the code only working when added to an existing function, but not as its own?
I'm assuming that by "its own" you are referring to this:
document.getElementById("convert").onclick = sound();
In this case, you are assigning the returned value of sound() to the onclick property of the element. If you want sound to be called when the button is clicked, remove the parenthesis:
document.getElementById("convert").onclick = sound;
Demo:
function sound(){
var audio = new Audio("https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3");
audio.play();
}
document.getElementById("convert").onclick = sound;
<button id="convert">Play</button>
I have in my index.html this already, and then i add a function named play where i call in play to my script file[then finally when i try to call in my play command if the player decides to shoot a fireball at the enemy it gives me an error saying "Cannot read property 'play' of null" What do i do?
I have this in my index.html file:
<audio id="audio" src="fire.mp3" ></audio>
At the top of my script file, i do this:
var fire = new Audio();
fire.src = "fire.mp3";
function play(){
var audio = document.getElementById("audio");
audio.play();
}`
(Fire.mp3 is already a file outside of my program, its what i called in in my index.html file)
Lastly, when the player decides to use fireball, I tried to add the one second fireball noise in by doing this:
if (fire = true && up2 === "FIRE" ) {
var enemyhealth = parseInt(enemyhealth) - parseInt(firepower);
xp + 2;
play();
`
play at the end is when i try to call in the function, but it dosent work.
You're using inconsistent methods and objects. Change your code to this:
var fire = document.getElementById("audio");
Or this:
var fire = new Audio("fire.mp3");
And then make sure it's still consistent all the way through your program.
I have several long stories which for which the source audio is sentence-by-sentence audio files. I would like to create a web page where one could listen to individual sentences of a particular story many times, or listen to the whole story from start to finish.
To start, my web page has many <audio> elements, each of which is in a <p> with the corresponding text. Each of these <audio> elements corresponds to a single sentence of the story.
I was about to start coding up a javascript object which was going to allow some sort of "play all" functionality, you'd click the button and it would play audio[0], when that finished, audio[1], etc. It would also have a 'pause' button and keep track of where you were, etc. This way the individual sentences could still be played or enjoyed because they each have an audio element. Or, one could use my "play all" buttons at the top to treat the sequence of audio elements as if they were one big element.
Then I started asking myself if there's some better/easier/more canonical solution here. One thing I thought of doing would be to cat all of these individual audio files together into a big audio file and perhaps create 'chapter' <track> elements. Is this preferable?
What are the pros and cons to each approach? Is there some out-of-the-box solution already made for me which I simply haven't turned up?
You could use the ended event to play the next sound when the previous sound completes (Playing HTML 5 Audio sequentially via Javascript):
var sounds = new Array(new Audio("1.mp3"), new Audio("2.mp3"));
var i = -1;
playSnd();
function playSnd() {
i++;
if (i == sounds.length) return;
sounds[i].addEventListener('ended', playSnd);
sounds[i].play();
}
function playAudio(src) {
var audioElement = new Audio(src);
audioElement.play();
return audioElement
}
const sequences = ['./audio/person.m4a', './audio/4.m4a', './audio/5.m4a', './audio/6.m4a', './audio/6.m4a', './audio/6.m4a', './audio/room.m4a', './audio/3.m4a']
// play audio
let index = 0
const audioElement = playAudio(sequences[index])
audioElement.addEventListener('ended', (e) => {
index++
if (index < sequences.length) {
audioElement.src = sequences[index]
audioElement.play();
}
})
I use javascript to solve the problem, using Audio objects and a setInterval. Below an example:
var sndLetItSnow = new Audio("audio/letItSnow.m4a");
var sndSanta = new Audio("audio/snow.m4a");
var playlist = [sndLetItSnow, sndSanta];
var current = null;
var idx = 0;
function playSound() {
if (current === null || current.ended) {
// go to next
current = playlist[idx++];
// check if is the last of playlist and return to first
if (idx >= playlist.length)
idx = 0;
// return to begin
current.currentTime=0;
// play
current.play();
}
}
setInterval(playSound, 1000);
For more documentation on Audio object you can visit this page:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement
I hope this help!
I am using an audio-player package to play a sound locally when a node app triggers an event. When the event is triggered, a function is called with the specific file that needs to be opened as such:
playSound(fileName);
The separate function looks like this:
player = new Player('someDirectory/' + fileName + '.mp3');
player.play();
This opens and begins playing the file perfectly well, however when events trigger in quick succession, both sounds will be simultaneously playing. While I initially thought to simply add a:
player.stop();
before the 'new Player' definition, the previous instance is clearly out of scope, as the function has been called a second time. How can I stop all other instances of Player before starting playback anew?
You need to declare the player variable in the outer scope, so that every function "sees" the same player.
var player;
function playSound(fileName) {
if (player) {
player.stop();
}
player = new Player(fileName);
player.play();
}
This is called a closure.
Your player should be static, only one instance should exist and play all sounds.
function Podcast() {};
Podcast.FILE_EXTENSION = 'mp3';
Podcast.download = function(podcast) {
console.log('Downloading ' + podcast + ' ...');
};
Here we created a constructor function named Podcast with a static property called FILE_EXTENSION and a static method named download.
http://elegantcode.com/2011/01/19/basic-javascript-part-7-static-properties-and-methods/
I have many small audio files, and I want to play these files one after another, not all of them at the same time. I have used the object Audio in javascript like this
var audio_1 = new Audio();
var audio_2 = new Audio();
var audio_3 = new Audio();
audio_1.src = "/path1";
audio_2.src = "/path2";
audio_3.src = "/path3";
Now I just need to call the function play for every object, but I need to play the audio_1 alone, and play audio_2 when the first one ended.
The solution I found is to test on the property ended of every object
audio_1.ended; // returns true when it ends playing
I found an object onended inside the audio object, I thought it's a function but it's not, can someone help me and give me the best way to solve this problem.
use addEventListener instead of assigning a function to the onended property:
audio.addEventListener('ended', function() {}); // Do
audio.onended = function() {}; // Don't
So, a IMHO dirty way is this:
audio_1.play();
audio_1.addEventListener('ended', function() {
audio_2.play();
audio_2.addEventListener('ended', function() {
audio_3.play();
};
};