How to properly pause or stop audio track with javascript?, I tried this:
var track1 = new Audio('track1.mp3');
$('#play').click(function() {
track1.play();
});
$('#stop').click(function() {
track1.stop();
});
It plays but can't make it stop, I'm basically trying to make an small player with the basic options, super simple without using any framework.
Audio elements don't have a "stop" method. I think you may be looking for track1.pause() instead.
Reference to HTMLMediaElement methods and properties: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement
Related
First of all, hello.
I have to develop a simple game in flash, usign HTML5 Canvas and JavaScript. The game, however poor, is pretty much implemented. My problem is, that after you play the game, it shows a try again button, designed to go back to frame 1. When i click the button it goes to frame 1 and returns to frame 25. Any ideas?
The last frame has this code:
var root = this;
this.stop();
this.tryAgain_btn.addEventListener("click", mouseClickHandler);
function mouseClickHandler(e) {
root.gotoAndPlay(0);
};
And frame one has this code:
var self = this;
this.stop();
this.play_btn.addEventListener("click", go);
function go()
{
self.gotoAndPlay(1);
}
Any ideas on how to solve this? Thank you.
Are you developing this in html5 or in actionscript? Based on your picture of your timeline it looks like you're using actionscript, not a HTML5 Canvas with javascript.
Besides that, try using gotoAndStop(1); rather than gotoAndPlay(0) and removing your stop(); methods. Let me know in the comments if it works but since your question is slightly unclear I don't have a grasp on what you're doing.
EDIT
Example, in case you don't understand:
var root = this;
this.stop();
this.tryAgain_btn.addEventListener("click", mouseClickHandler);
function mouseClickHandler(e) {
root.gotoAndStop(1);
}
EDIT 2
Take a shot at using
this.tryAgain_btn.addEventListener("click", function (event)
{
this.gotoAndPlay(1);
});
I am building a small video player with Javascript for a website. I have a list with videos in JSON. I instantiate my player with
var Videoplayer = new myVideoPlayer(data);
Because the list contains videos from Vimeo and YouTube, I want to handle both APIS inside this object. Inside I have functions like:
setVideo(videoId)
to select and play a video, or
markVideoAsSelected(video)
to add classes in html.
So far everything went pretty smooth, but I am hitting a wall now. When I load the YouTube player via the API, I add the:
events : {
'onStateChange': self.YTonStateChange
}
Everything I want is bound to the Videoplayer instance I created in the beginning. On state change, I run this:
YTonStateChange : function(e){
var self = this
switch(e.data){
//Video ended code 0
case 0:
setTimeout(self.switchToNextVideo, 3000);
break;
}
}
The problem:
this is now bound to the event from the YouTube API and I lost my object. I don't know, how I can pass my object instance along with the event to the event handler?! There are things in there that I need for further steps, how can I get it back?
Just bind the context to 'self' like that :
events : {
'onStateChange': self.YTonStateChange.bind(self)
}
It will force 'this' value to 'self' in the YTonStateChange callback. Hope it helps ;)
Code I am creating is a function which with the function it should .play() it... here is the code
function playSound() {
document.getElementById('newMessage').play();
}
var sound = document.createElement('audio');
sound.setAttribute("src","http://www.soundjay.com/button/beep-2.wav");
sound.id="newMessage";
sound.setAttribute('autoplay','false');
document.body.appendChild(sound);
Though everytime in console trying to do playSound(); it says playSound is undefined. So then I try doing document.getElementById('newMessage').play(); and it doesn't play either, nor does $('#newMessage').play(); which comes with an error of object [object Object] has no method play.
Any suggestions as this is the first time trying to dynamically create the audio file and use a function to play it. I've looked at a few other SO topics and well they don't seem to be leading me in the right direction. Thanks
My guess is you're defining the playSound method after the page has already loaded, maybe in some onload method. If this is the case, try attaching the method to the window object:
window.playSound = function() {
document.getElementById('newMessage').play();
}
This is make the function available even if the function is defined after the page loads. Also you shouldn't set autoplay to false. It defaults to false, and if you want to set it to true you set autoplay="autoplay".
JSFiddle
I'm creating my own HTML5 audio player capable of handling playlists. I have created a custom myPlaylist object with includes all play(), pause(), stop() and other needed functionality. This is all working correctly, but moreover, I need to be aware about when an audio file has ended in order to automatically start playing the next one.
Here's the relevant parts of the code I'm using:
function myPlaylist(){
var player = document.createElement('audio');
var audio = $(player).get(0);
this.next = function next(){
// Picks next song in the playlist and plays it
...
};
$(audio).bind('ended', function() {
alert("Song is finished!");
// Here I want to call to my next() function
});
}
I haven't been able to figure out how to do it. I've tried already several combinations, like $(this).next(), which seems the most reasonable and actually displays the alert, but then does nothing ¿?, also this.next(), which also displays the alert but then shows an error since this refers to the HTML5 audio element, which does not have a next() function.
I've also tried another approach, using
audio.onended = function(){
alert("Song is finished!");
$(this).next();
};
But those do not even trigger the alert. Also audio.ended does not work.
So, I'm basically clueless right now, does anyone have any idea what am I doing wrong? Thanks in advance.
Oh, and I've tested all this in the latest versions of Google Chrome and Safari in Mac OS X.
EDIT Following the advice given in HTML5 audio playlist - how to play a second audio file after the first has ended?, I've also tried the following code
player.addEventListener("ended", function() {
alert("Song is finished!");
$(this).next();
});
And
player.addEventListener("ended", next);
None of them work either, although the first one shows the alert properly.
EDIT 2 Using the search I came across this question, which might also have something to do with my problem, so in order to get rid of any possible troubles with the reference to this, I added a new variable referring to the object itself, so now I'm basically working with:
function myPlaylist(){
var player = document.createElement('audio');
var audio = $(player).get(0);
var me = $(this);
this.next = function next(){
// Picks next song in the playlist and plays it
...
};
$(audio).bind('ended', function() {
alert("Song is finished!");
me.next();
});
}
But then I get an error saying that the Object does not have a method next().
I don't know what else can I try... Any extra information will be highly appreciated, thank you!
there's an HTML5 playlist example handling the ended event here, if that helps?
in your event handler you reference this, but in this context this refers to the DOM element that caught the event, i.e. your audio element.. try this instead:
function myPlaylist(){
var self = this;
var player = document.createElement('audio');
this.next = function (){
// Picks next song in the playlist and plays it
...
};
player.addEventListener("ended", function() {
alert("Song is finished!");
self.next();
});
}
see the MDN for more info on the this keyword
With Javascript, I have a function that creates an audio element with createElement("audio"), and start playing in loop without using appendChild(), I mean without appending it to the DOM.
The element created is kept in a variable, let's called it music1:
music = document.createElement("audio");
music.addEventListener("loadeddata", function() {
music.play();
});
music.setAttribute("src", music_Source);
What I would like to do, is to change the music played, if possible using the same function, and storing the element in the same variable.
What I do is that before the code above:
if(typeof(music) == "object") {
music.pause();
music = null;
}
But: if I remove music.pause(), the first music keeps playing, and the second starts playing too at the same time, which makes me think that the first music is always somewhere in the document/in the memory. Also, music = null seems useless. I don't want to use jQuery.
Do you have any idea to properly remove the first music, delete the element, or so on?
Actually, kennis' comment is right, I tried to just change the src attribute, and not modify the "music" variable (neither setting it to null, nor re-creating an Element) and it seem to work too. So, for the record: For each source changing here is the function:
if(typeof(music) != "object") {
//audio element does not exist yet:
music = document.createElement("audio");
music.addEventListener("loadeddata", function() {
music.play();
});
}
music.setAttribute("src", music_Source);
rather than delete, the better way of doing it would be to change the src
music.setAttribute('src',theNewSource); //change the source
music.load(); //load the new source
music.play(); //play
that way you're always dealing with the same object so you hit the DOM less often, and also you avoid your problem of having two player at the same time
Also make sure you use the .load method to load the new audio, otherwise it will keep playing the old one.
The original object would be deleted, but only when the garbage collector determines that it's time. The fact that it's audio may complicate things and make it difficult for the browser to make that determination.
So, yes, just re-use the original object instead.
While reusing the HTMLAudioElements is definitely the best option -for completeness- you should be able to dispose it by just clearing the src or srcObj:
music.srcObj = null;
This more or less lets the GC of your browser know that the element is ready for removal.