audio.play() working within existing function but not as lone function - javascript

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>

Related

How do i add audio to my program? I have a mp3 already in my program

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.

How to stop a video using stop function?

Alright, I have very little programming experience and just want to make controls for video and audio pieces together on one page. I have searched a lot and can't figure it out.
var stop = function (id) {
.pause();
.src = '';
};
I want to pass either the audio or videos' id as the parameter in my function but I don't understand how make code that can be used with either. I can't put id.pause(); into my function to pause whatever id I put in as a parameter, so I'm confused as to how to make it work. Any help is appreciated!!
You could use JQuery:
$('#playMovie1').click(function(){
$('#movie1').get(0).play();
});
Or you could do something like this:
function playVid(x) {
var vid = document.getElementById(x).pause();
}
You can use
var stop = function (htmlId) {
var vid = document.getElementById(htmlId);
vid.pause();
};
If you are passing the id then use that id to pause or play
var stop = function (id) {
$('#'+id).pause(); // to pause the video
.src = '';
};

Out of Scope Objects in NodeJS

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/

Playing audio files in javascript

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();
};
};

Javascript method pause() only works with audio element

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();
}

Categories