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
Related
Currently working on a page containing a video that has to be paused at certain points (like chapters). So I made a function that will stop the video when it hits the next "time marker" which looks like this:
function vidPause(nextMarker){
var timeMarker = nextMarker;
if(videoPlayer.currentTime >= timeMarker) {
videoPlayer.pause();
videoPlayer.removeEventListener('timeupdate', vidPause());
}
};
And I'm trying to fire it this way:
videoPlayer.addEventListener('timeupdate', vidPause(nextMarker));
But it only seems to fire when the video is loaded. Nothing happens when the video is playing (tested by using a console.log(videoPlayer.currentTime); inside the vidPause function).
Note: I need the function to be called that way so that I can remove the event listener when it hits the time marker, that way it won't stop when the user wants to play the video from that point on.
Thanks in advance for any suggestions!
The function is being called once in the addEventListener line, but that's not actually passing it as a callback.
Try this:
function videoUpdate(e) {
vidPause(nextMarker, videoPlayer.currentTime;); // Now call your function
}
function vidPause(nextMarker, timeStamp){
var timeMarker = nextMarker;
if (timeStamp >= timeMarker) {
videoPlayer.pause();
videoPlayer.removeEventListener('timeupdate', videoUpdate);
}
};
videoPlayer.addEventListener('timeupdate', videoUpdate); // Note no brackets, as it's passing a ref to the function rather than calling it
I don't know what the scope of nextMarker is, but you should be able to start console logging and find out.
I am trying to get an event fired once the youtube video reached its end.
The video embedding works, but nothing happens once the video ends.
I think I am missing something for the EventListener...
this is my code:
var params = { allowScriptAccess: "always" };
var atts = { id: "myytplayer" };
var video = swfobject.embedSWF("http://www.youtube.com/v/elvOZm0d4H0?enablejsapi=1&playerapiid=ytplayer&version=3&rel=0&autoplay=1&controls=1","ytapiplayer", "450", "250", "8", null, null, params, atts);
XXXXX.addEventListener("onStateChange", function(state){
if(state === 0){
alert("Stack Overflow rocks!");
}
});
What I do not get is, what I should listen to?
Marked with "XXXXX" in the code, what do i need to put there? I tried myytplayer, video, ytplayer, ytapiplayer... most of them give me an error, e.g. "ytplayer can not be found".
"ytapiplayer" did not throw an error, but also nothing happens once the video is finished playing.
I searched stack Overflow, but all the "answers" I found so far are just naming this event listener, but do not explain what I have to put at "XXXXX".
I am pretty new to this and any help is very welcome, thanks!
JSFIDDLE: http://jsfiddle.net/T5HBZ/
edit: edited code for controls, added jsfiddle
Here's your working code, and then I'll explain it:
var params = {
allowScriptAccess: "always"
};
var atts = {
id: "myytplayer"
};
var video = swfobject.embedSWF("http://www.youtube.com/v/elvOZm0d4H0?enablejsapi=1&playerapiid=ytplayer&version=3&rel=0&autoplay=1&controls=1", "ytapiplayer", "450", "250", "8", null, null, params, atts);
onYouTubePlayerReady = function (playerId) {
ytplayer = document.getElementById("myytplayer");
ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
};
onPlayerStateChange = function (state) {
if (state === 0) {
alert("Stack Overflow rocks!");
}
};
The first thing is to note that, when you embed the player SWF with swfobject, you are telling that library to REPLACE the div you reference with the one generated by swfobject. So the ytapiplayer div will no longer exist, but there will be an element with the id of 'myytplayer.' Note that, when you append the 'enablejsapi=1' to your swf URL, then the swf will load the video AND load the javascript allowing you to control the video.
This is key; when that javascript is done loading, it will automatically call a function named "onYouTubePlayerReady" -- there isn't a way to change that name, as it's part of the javascript loaded from youtube. If you don't define that function, nothing happens. If you do define that function, though, you have the opportunity to start interacting with the player.
So what your code was missing was a definition of that function, within which you add an event listener directly onto the element that was created by swfobject (it HAS to take place inside this function; if you try to do it outside of the callback, the object might not exist yet).
Also note that, for some reason, it seems to be more consistently workable to have the event listener reference an actual function as its callback (rather than an anonymous one), so you'll see that in the code as well.
Of course, all this discussion can be superseded by pointing out that you might be much better served by using the iFrame player API instead of the SWF/Javascript API. The info is here:
https://developers.google.com/youtube/iframe_api_reference
It's a similar methodology, in that you load a javascript library, which automatically will call a callback that you define, inside of which you set up your bindings to the player, add event listeners, etc. The real advantage is that it will determine whether to serve the HTML5 or the Flash player automatically, with the API on your side being able to talk to either player.
I built a player on top of videoJS and I'm having trouble accessing public functions inside videoJS .ready(). The thing is that my code appears to be working everywhere except IE (works in chrome, safari, ff, etc.):
var myPlayer = _V_('myvideojsId');
myPlayer.ready(function() {
var player = this;
player.myPublicFunction = function() {
alert("hey!");
}
});
myPlayer.myPublicFunction();
In IE I get
Object does not support this property or method
on the myPlayer.myPublicFunction() line. Are the other browsers letting me get away with bad code or is this IE's fault?
Any help would be great, thank you!
Chris
Referencing their documentation, it shows exactly what Jonathan has said:
https://github.com/zencoder/video-js/blob/master/docs/api.md#wait-until-the-player-is-ready
He's right about IE by the way. As much as we all love to hate it, it has found real issues for me many times.
Just for quicker reference, here's an alternative to your method to getting this done:
_V_("example_video_1").ready(function(){
var myPlayer = this;
// EXAMPLE: Start playing the video.
myPlayer.play();
});
This is likely a problem with timing:
myPlayer.ready(function() {});
myPlayer.myPublicFunction();
Your first line here hands off a function to myPlayer to call whenever the player is ready. This doesn't happen immediately in most cases, so there is most likely a delay. This means your public function isn't added to the myPlayer object immediately, but rather this task will be accomplished whenever the video player is ready.
All of this means that when JavaScript moves on to the second line, the appropriate response from a browser is that the method doesn't exist - because it doesn't. It won't exist until the video player is ready, which isn't until later.
You could use more of a feature-detection approach, and only call the method if it exists:
if (myPlayer.myPublicFunction) {
myPlayer.myPublicFunction();
}
You could also just add the method before-hand:
myPlayer.myPublicFunction = function () { alert("Foo"); };
myPlayer.ready(callback);
myPlayer.myPublicFunction(); // 'Foo'
In the end, I've found that Internet Explorer is not as forgiving (which is good) as some other browsers. If it's acting up today, it's likely because there's a problem in the code.
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
I am trying to write a script so that when I play an embedded sound object, a picture that I also have embedded will change.
function changePic() {
document.getElementById("sound").onclick = transform(document.getElementById("pic"));
}
function transform (pic) {
pic.src = "";
alert ("done");
}
The problem is that when I load the page, the Javascript code automatically runs even though I don't click play (autostart is set to false) on the sound object. Does anyone have an idea as to what is causing this?
When you write onclick = transform(...), you're calling transform and assigning the result to onclick.
You need to set the handler to an anonymous function that calls transform, like this:
document.getElementById("sound").onclick = function() {
transform(document.getElementById("pic"));
};
However, this is the wrong way to add events.
You should call element.addEventListener / element.attachEvent. (or just use jQuery)