automatically play next soundcloud - javascript

I'm currently working on my music blog, and I'm trying to make the widgets start when previous one finishes. I have both soundcloud and youtube widgets, but the priority is to implement this functionality for the soundcloud ones.
Each iframe has 2 class .widget &.soundcloud_widget for soundcloud and .widget & .youtube_widget for youtube. Finally, each widget gets an id "widget1", "widget2", etc... in the order of apparition.
The idea would be to get the event "SC.Widget.Events.FINISH" , to get the id of the corresponding widget, "increment" it, and then make the next one play.
Unfortunately, I'm struggling with javascript & the documentation of soundcloud, and I would really appreciate some help !
Thanks in advance
PS : here is the code that does the above, I have nothing else that is usable...
<script type="text/javascript">
function autoPlayInitiate () {
var i=1;
$("iframe[src^='https://w.soundcloud.com/']").addClass("widget soundcloud_widget");
$("iframe[src^='//www.youtube.com']").addClass("widget youtube_widget");
$('.widget').each(function(){
$(this).attr('id','widget'+i);
i++;
});
}
window.onload = autoPlayInitiate;
$(document).ready(function () {
var ScWidget = $('.soundcloud_widget');
}
</script>

So first off I think the simplest way for you to solve this problem is to pick one of the players (either youtube or soundcloud) and use there playlist features to showcase your sounds.
here is a live example of using a playlist in Sound Cloud you can play with
http://runnable.com/UuhEs3Yq2_8hAACT/embbed-soundcloud-widget-using-javascript
relevant code:
function embed (id) {
SC.oEmbed("http://soundcloud.com/" + id // user or playlist to embed
, { color: "ff0066"
, auto_play: true
, maxwidth: 500
, maxheight: 1000
, show_comments: true } // options
, document.getElementById("scWidget") // what element to attach player to
);
}
$(document).ready(
function () {
embed("dj-faze");
}
);
however if you wish to go the long route you will want to familiarize yourself with the widget API:
http://developers.soundcloud.com/docs/api/html5-widget#
the bind(eventName, listener) is what you would be most interested in
var iframeElement = document.querySelector('iframe');
var iframeElementID = iframeElement.id;
var widget = SC.Widget(iframeElement);
widget.bind(SC.Widget.Events.FINISH, function () {
alert('add code to play next song here')
});
I will try to put up a new example on runnable once the site has finished its maintenance

Related

Flowplayer playlist setPlaylist(array) does not change playlist dynamically

On the page a have a flowplayer which play videos by provided tag (just a name of video category) using playlist plugin. And I have section “Suggested videos”. When I click on suggested video, I want to reload playlist using newly selected video tag. I tried use setPlaylist(array) as described in documentation https://flowplayer.org/docs/playlist.html#methods:
var player = flowplayer();
player.setPlaylist(this.playlist);
but it's not working.
Full player method code:
updatePlayer() {
if(document.getElementById('flow').innerHTML === "") {
var player = flowplayer(document.getElementById("flow"), {
autoplay: true,
playlist: this.playlist,
loop: true
});
// here I add all player events what I need
} else {
console.log('player updated');
var player = flowplayer();
player.unload();
//update flowplayer playlist
player.setPlaylist(this.playlist);
}
}
When the player is initialized and I click to suggested videos console.log() shows me message and player.unload() works, but setPlaylist() doesn't.
The only solution what can help its to use shutdown() method, which destroys all player instances, events and so on. But it is an ugly solution I think, previous I used JW player where you can easily update playlist dynamically.
Can anyone help me? Thanks!
Solution is player.setPlaylist(this.playlist).play(0);

Stop any embeded YouTube iframe when another is played

I am embedding about 10 YouTube iframes in my page, all with their own custom play/pause buttons. I have used this solution to begin http://jsfiddle.net/buuuue/dzroqgj0/ but I'm not sure how to tweak this piece of the code to stop ANY other video that is playing if another one begins...
function stopVideo(player_id) {
if (player_id == "player1") {
player2.stopVideo();
} else if (player_id == "player2") {
player1.stopVideo();
}
}
For example, if player 1 is currently playing, and player 3 is played, I'd want player 1 to stop playing. I've also looked into this solution https://stackoverflow.com/a/38405859/1798756, but I think I need to create the players via JS so that I can also create the custom play/pause buttons.
Thanks in advance for any help!
After creating players push them onto an array.
var vids =[];
player1 = new YT.Player('player1', {
//stuff
});
vids.push(player1);
player2 = new YT.Player('player2', {
// stuff
});
vids.push(player2);
....
..
playerN = new YT.Player('playerN', {
// stuff
});
vids.push(playerN);
Every player object's id can be accessed by its a.id property(a is itself an object , id is a property(string) )
Now when user plays a given player you have to just pause all other except the one being played(id of which you get in stopVideo).Since you have id it's easy
function stopVideo(player_id) {
for(var i=0;i<vids.length;i++){
if (player_id !=vids[i].a.id)
vids[i].stopVideo();
}
}
Example : - http://jsfiddle.net/4t9ah1La/
If you are not creating player through scripts but rather just embedding iframes then this answer mentioned by vbence is enough , below is a demo of that with improvements suggested by Jennie
Example : - http://jsfiddle.net/fyb7fyw1/
All credits to respective original authors

How to play audio only from youtube videos using HTML and javascript

What I'm trying to do: Create a list of items which contains a link to play audio from a youtube video beside each item
What I'm currently doing: I'm able to do this for a single item using the below:
<div data-video="VIDEO_ID"
data-autoplay="0"
data-loop="1"
id="youtube-audio">
</div>
<script src="https://www.youtube.com/iframe_api"></script>
<script src="https://cdn.rawgit.com/labnol/files/master/yt.js"></script>
This creates a play button and works perfectly on a single item, however will not work with multiple items on the same page presumably since they all use the same ID. Creating a different ID causes the player to not function. Creating two different data-video's with the same ID will only allow the first one to play, the other will appear correctly but not operate when pressing play.
Looking for solution: Preferably how to use the existing script for multiple videos on the same page. Otherwise an alternative solution for playing audio only on youtube videos with a custom play button would be great.
Thanks!
If you want you can just copy paste your code like this
https://jsfiddle.net/8wkjqf3m/
and it works, I'm not sure if you were having a problem doing that or if your problem was elsewhere. It is of course very sloppy looking and the code should be reworked so that you don't have to hard code every function for every video.
I tried to do everything dynamically and failed. I'm not sure if it is possible to dynamically make a function that makes a "new YT.player" for every video id you have and also have the onPlayerReady and onPlayerStateChange functions dynamically made to go with it. I'm sure there is some way but I couldn't figure it out.
The idea though is to make multiple "youtube-audio" divs with different ids for however many youtube players you want to have and have matching multiple "youtube-player" divs for the iframe to function. You can generate that part with javascript if you want so that you don't have to pollute your code with a bunch of repetitive html.
You can make all of your ids dynamically too.
var array = ['put a video id here','put a video id here','put a video id here'];
array = array.map(function(element,index) {
var div = document.createElement('div');
div.setAttribute('id', 'youtube-audio-' + index);
return {'videoId': element, 'div': div };
}
You can just have an array holding the youtube video ids and then initialize all of the divs data-video attributes using
document.getElementById("youtube-audio-1").dataset.video = //youtube video id
I don't see the point in doing all of that dynamically though if there is no way to get around copy pasting x number of "new YT.player"s and "onPlayerReady"s etc...
Good Luck, let me know if I was in the right area or if that was not what you wanted
I have modified the second script so it works as you (or I) want.
To use it use classes instead of IDs. Like the following:
<div data-video="NQKC24th90U" data-autoplay="0" data-loop="1" class="youtube-audio"></div>
<div data-video="KK2smasHg6w" data-autoplay="0" data-loop="1" class="youtube-audio"></div>
Here is the script:
/*
YouTube Audio Embed
--------------------
Author: Amit Agarwal
Web: http://www.labnol.org/?p=26740
edited by Anton Chinaev
*/
function onYouTubeIframeAPIReady()
{
var o= function(e, t)
// This function switches the imgs, you may want to change it
{
var a=e?"IDzX9gL.png":"quyUPXN.png";
//IDzX9gL is the stopped img and quyUPXN the playing img
t.setAttribute("src","https://i.imgur.com/"+a)
// folder or web direction the img is in. it can be "./"+a
};
var counter = 0;
var bigE = document.querySelectorAll(".youtube-audio");
bigE.forEach(function(e)
{
var t=document.createElement("img");
t.setAttribute("id","youtube-icon-"+counter),
t.style.cssText="cursor:pointer;cursor:hand",
e.appendChild(t);
var a=document.createElement("div");
a.setAttribute("id","youtube-player-"+counter),
e.appendChild(a);
t.setAttribute("src","https://i.imgur.com/quyUPXN.png");
e.onclick=function()
{
r.getPlayerState()===YT.PlayerState.PLAYING||r.getPlayerState()===YT.PlayerState.BUFFERING?(r.pauseVideo(),
o(!1, t)):(r.playVideo(),
o(!0, t))
};
var r= new YT.Player("youtube-player-"+counter,
{
height:"0",
width:"0",
videoId:e.dataset.video,
playerVars:
{
autoplay:e.dataset.autoplay,loop:e.dataset.loop
},
events:
{
onReady:function(e)
{
r.setPlaybackQuality("small"),
o(r.getPlayerState()!==YT.PlayerState.CUED, t)
},
onStateChange:function(e)
{
e.data===YT.PlayerState.ENDED&&o(!1, t)
}
}
})
counter++;
});
}

Pause a Vzaar Video in a Bootstrap Modal

Video in a Bootsrap modal continues to play when the modal is closed.
I have found solutions for YouTube video and html5 video but i am using Vzaar Video and Vzaar's API java script
I have it working from the close button in the modal (using id="video-btn") but I really need it to work also if clicking outside of the modal, or I guess on data-dismiss="modal", which should cover all (?).
Not being great with java, help would be appreciated.
My code just for the close button (which works fine) is below.
// Vzaar
window.addEventListener("load", function() {
var player = new vzPlayer("vzvd-XXXXXXX");
// adding pause() API method to DOM element:
var myPauseButton = document.getElementById("video-btn");
myPauseButton.addEventListener("click", function() {
player.pause();
});
});
I have solved it:
// add listener vzaar video //
window.addEventListener("load", function() {
var player = new vzPlayer("vzvd-xxxxxxx");
// adding pause() API method to hidden.bs.modal: //
$('#myModalId').on('hidden.bs.modal', function () {
player.pause();
});
});
(of course http://player.vzaar.com/libs/flashtakt/client.js needs to be included)

Getting Current YouTube Video Time

I am writing a Browser Plugin and need to find a way to get the current time a YouTube Video playing on YouTube using JavaScript. I have been playing around in the Chrome JavaScript Console and haven't had any luck.
It appears that the chrome API only works with embedded video players not a video that is playing on on youtube.com. One option I looked into is in the share section of a video their is an input box for the "start at:" time that contains the current time of the video. I have tried using .value and .text on this input box and they both return undefined? Does anyone have any ideas?
ytplayer = document.getElementById("movie_player");
ytplayer.getCurrentTime();
See the api
Update: if it didn't work, also try player.playerInfo.currentTime (codepen live example)
Depends on what you want
player.getCurrentTime():Number
Returns the elapsed time in seconds since the video started playing.
player.getDuration():Number
Returns the duration in seconds of the currently playing video. Note
that getDuration() will return 0 until the video's metadata is loaded,
which normally happens just after the video starts playing.
http://code.google.com/apis/youtube/js_api_reference.html
Finally I found how to make it work on iOS (and Android too).
Actually, the whole youtube js api was broken for me if run on mobile browser.
Problem solved by creating player using new YT.Player as described in YouTube IFrame API.
Please note: only creating <iframe> from <div> placeholder works for mobile browsers at the time. If you try to use existing <iframe> in new YT.Player call, as mentioned in IFrame API, this will not work.
After player created, it's possible to use player.getCurrentTime() or player.getDuration() with player instance created.
Note: I had no luck calling this methods on player obtained with
player = document.getElementById(...) (from #JosephMarikle answer).
Only created player instance worked in mobile browsers.
Useful links:
YouTube IFrame API
YouTube JavaScript API
YouTube Player Demo
You can use Html5 Video API on youtube.com
var htmlVideoPlayer = document.getElementsByTagName('video')[0];
htmlVideoPlayer.currentTime
Note: It's not gonna work on Youtube Iframe API because Iframes are isolated. You cannot access the context of a Youtube IFrame .
In 2020, this works:
player.playerInfo.currentTime
full code:
see it live on codepen
Just FYI, There is a new iframe API for the YouTube player:
https://developers.google.com/youtube/iframe_api_reference
document.querySelector('video').currentTime
Stop at specific time youtube video and show notification box in GWD
<script>
var yid = document.getElementById("gwd-youtube_1");
var idBox = document.getElementById("box1");
pausing_function = function(event) {
var aa = setInterval(function() {
if (yid.getCurrentTime() > 8.0 && yid.getCurrentTime() < 8.1) {
yid.pause(yid);
idBox.style.opacity = 1;
console.log(yid.getCurrentTime() + "playing")
clearInterval(aa);
yid.removeEventListener("playing", pausing_function);
}
}, 100)
}
yid.addEventListener("playing", pausing_function);
var pausing_function_1 = function() {
if (yid.getCurrentTime() > 8.1) {
console.log(yid.getCurrentTime() + "pause")
// remove the event listener after you paused the playback
yid.removeEventListener("playing", pausing_function);
}
};
</script>
play video and hide notification
<script type="text/javascript" gwd-events="handlers">
window.gwd = window.gwd || {};
gwd.pauseVideo = function(event) {
var idBox = document.getElementById("box1");
idBox.style.opacity = 0;
};
</script>
<script type="text/javascript" gwd-events="registration">
// Support code for event handling in Google Web Designer
// This script block is auto-generated. Please do not edit!
gwd.actions.events.registerEventHandlers = function(event) {
gwd.actions.events.addHandler('gwd-youtube_1', 'playing', gwd.pauseVideo, false);
};
gwd.actions.events.deregisterEventHandlers = function(event) {
gwd.actions.events.removeHandler('gwd-youtube_1', 'playing', gwd.pauseVideo, false);
};
document.addEventListener("DOMContentLoaded", gwd.actions.events.registerEventHandlers);
document.addEventListener("unload", gwd.actions.events.deregisterEventHandlers);
</script>

Categories

Resources