I am trying to have my player go to next song but I cant seem to get my code to work. So far play and pause work perfectly but the next function is not responsive.
SC.get("/tracks/316493713").then(function(response) {
console.log(response);
})
SC.get("/tracks/323674116").then(function(response) {
console.log(response);
})
//create an object to hold track id and SC stream
function SoundCloud(){
this.trackId = [316493713,323674116]
this.song = SC.stream('/tracks/' + this.trackId[index])
}
var jukebox = new SoundCloud();
//play
SoundCloud.prototype.play = function() {
this.song.then(function(player) {
player.play();
})
}
//pause
SoundCloud.prototype.pause = function(){
this.song.then(function(player){
player.pause();
})
}
//next functionality not working.
SoundCloud.prototype.next = function(){
this.song.then(function(player){
if(index === this.song.length-1){
index =0;
} else {
index++;
}
this.song.currentTime = 0;
this.song.play();
})
}
Related
i am having trouble with a script.
It works fine the first time, but when I go to another page on the site and then back to the front page the site does not load fully. I need to press refresh for it to work properly.
Does anyone have an idea why that might be?
http://wordpress.juliebrass.com/
I tried to put it inside a window.addEventListener('load', function () {
But it did nothing
This is the code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// var figure = $(".video");
// var vid = figure.find("video");
// [].forEach.call(figure, function (item,index) {
// item.addEventListener('mouseover', hoverVideo.bind(item,index), false);
// item.addEventListener('mouseout', hideVideo.bind(item,index), false);
// });
// function hoverVideo(index, e) {
// video.play();
// }
// function hideVideo(index, e) {
// video.pause();
// }
(function($) {
window.addEventListener('load', function () {
function flickity_handle_wheel_event(e, flickity_instance, flickity_is_animating) {
// do not trigger a slide change if another is being animated
if (!flickity_is_animating) {
// pick the larger of the two delta magnitudes (x or y) to determine nav direction
var direction = (Math.abs(e.deltaX) > Math.abs(e.deltaY)) ? e.deltaX : e.deltaY;
console.log("wheel scroll ", e.deltaX, e.deltaY, direction);
if (direction > 0) {
// next slide
flickity_instance.next();
} else {
// prev slide
flickity_instance.previous();
}
}
}
var carousel = document.querySelector(".carousel");
var flickity_2 = new Flickity(".carousel", {wrapAround: true, freescroll:true});
var flickity_2_is_animating = false;
flickity_2.on("settle", function(index) {
console.log("Slide settle " + index);
flickity_2_is_animating = false;
});
flickity_2.on("select", function(index) {
console.log("Slide selected " + index);
flickity_2_is_animating = true;
});
// detect mousewheel event within carousel element
carousel.onwheel = function(e) {
flickity_handle_wheel_event(e, flickity_2, flickity_2_is_animating);
}
// video
var carousel = document.querySelector('.carousel');
var flkty = new Flickity( carousel );
function onLoadeddata( event ) {
var cell = flkty.getParentCell( event.target );
flkty.cellSizeChange( cell && cell.element );
}
var videos = carousel.querySelectorAll('video');
for ( var i=0, len = videos.length; i < len; i++ ) {
var video = videos[i];
// resume autoplay for WebKit
video.play();
}
var figure = $(".video");
var vid = figure.find("video");
$(".video > video").mouseenter( hoverVideo );
$(".video > video").mouseleave( unhoverVideo );
function hoverVideo(e) {
$(this).get(0).play();
}
function unhoverVideo() {
$(this).get(0).pause();
$(this).get(0).currentTime = 0;
//$(this).hide();
}
$(".feuer").mouseout(function() {
$("feuer").get(0).currentTime = 0;
});
$(".herz").mouseout(function() {
$("herz").get(0).currentTime = 0;
});
$(".stern").mouseout(function() {
$("stern").get(0).currentTime = 0;
$(".all").mouseout(function() {
$("all").get(0).currentTime = 0;
});
// your code
});
//pause on hover
})(jQuery);
</script>
I created, with some help, some javascript code to enable multiple operations to be accomplished when I press some buttons in my web app. It is working perfectly with the solution provided at the following link: One of Multiple Tasks Operated by Button Won't Execute provided by brk), but it is not working when I import the code into my CodePen text editor. There are three buttons, "online, offline, and all, which are upon being pressed, supposed to
switch the blue screen to black
hide the text that says, "PRESS BUTTONS BELOW"
hide the blinking --:-- symbol
However, when I press the "online", "offline", and "all" buttons, it almost seems as if nothing happens, because there is a short delay. Why does this delay happen? Also, the blinking --:-- symbol doesn't terminate blinking as it should...can you tell me why this is? Thanks so much in advance for the help!
See CodePen link here: https://codepen.io/IDCoder/pen/mXMqGV
Here is my javascript code:
var twitchTvStreamers;
var loaded = false;
$(document).ready(function(){
//GET TWITCH TV STREAMERS' STATUS AND API CALL
twitchTvStreamers=["FreeCodeCamp", "ESL_SC2", "OgamingSC2", "cretetion", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
//OUT OF ALL THE TWITCH TV STREAMERS IN A TWITCH TV ARRAY FIND THOSE 8 STREAMERS LISTED
});
//filter online offline and all
var filterchannel = filterch => {
if(!loaded)
{
for(channel of twitchTvStreamers){
getChannelInfo(channel, filterch);
}
}
else
{
setTimeout(function(){
$('.display-output-here div').each(function(idx, item) {
if($(item).hasClass(filterch))
{
$(item).show();
}
else
{
$(item).hide();
}
});
}, 100);
}
if(!loaded)
{
for(channel of twitchTvStreamers){
getChannelInfo(channel, filterch);
}
}
{
setTimeout(function(){
$('.text1 div').each(function(idx, item) {
if($(item).hasClass(filterch))
{
$(item).hide();
}
});
}, 100);
}
};//end of var filterChannel
$('button').click(function(e) {
filterchannel(e.target.id);
})
var getChannelInfo = (channel, filterch) => {
loaded = true;
$.getJSON('https://wind-bow.glitch.me/twitch-api/streams/' + channel)
.done(function(info) {
console.log(channel);
if (info.stream === null) {
appendInfo(channel,'offline',filterch);
}
else {
appendInfo(channel,'online', filterch);
}
});
}
var appendInfo = (channel,target, filterch) => {
$.getJSON('https://wind-bow.glitch.me/twitch-api/channels/' + channel)
.done( function(ch){
channelID = ch.display_name;
channelLogo = ch.logo;
channelUrl = ch.url;
streamContent = ch.content;
$('.display-output-here').append('<div class="' + target + ' all">'+channel+' is '+target);
if(twitchTvStreamers[twitchTvStreamers.length - 1] === channel) {
filterchannel(filterch);
}
});
//BUTTONS OPERATIONS (ALL BUTTONS TARGETED BY USING CLASS THEY COME UNDER)
$(".user-status").on('click', function() {
$(".text1").hide();
$(".text2").hide(function() {
clearInterval(x);
});
$('.display-output-here').css("background", "black");
$('.TV-screen').css("background", "black");
});
var element = $(".text2");
var shown = true;
var x = setInterval(toggle, 500);
function toggle() {
if (shown) {
element.hide();
} else {
element.show();
}
shown = !shown;
}
}
//make part of video-screen text blink
var element = $(".text2");
var shown = true;
setInterval(toggle, 500);
function toggle() {
if(shown) {
element.hide();
shown = false;
} else {
element.show();
shown = true;
}
}
//share-links code:
$('.Linkedinbutton').click(function() {
var shareurl = $(this).data('shareurl');
window.open('https://www.linkedin.com/shareArticle?mini=true&url=https://codepen.io/IDCoder/full/mXMqGV/' + escape(shareurl) + '&title=' + document.title + '&source=SourceTitle&target=new');
return false;
});
//Facebook
var facebookShare = document.querySelector('[data-js="Facebookbutton"]');
facebookShare.onclick = function(e) {
e.preventDefault();
var facebookWindow = window.open('https://www.facebook.com/sharer/sharer.php?u=' + document.URL, 'facebook-popup', 'height=350,width=600');
if(facebookWindow.focus) { facebookWindow.focus(); }
return false;
}
/*
//user status button operations
*/
//search bar operation
$("#searchStreamers").on("keypress",function(e){
var typeStreamer = $('input').val();
if(e.which===13){
$('input').submit(function(e){
e.preventDefault();
});
}
});
I want to play the songs only if the user press the button 'play',
without Waiting to load all the 21 songs.
when I press the button 'play' the page jump up like refreshing ,it is not normal.
what I can do to improve my code.
please try to play the songs in the example site and see the problem.
many thanks.
var Music = {
init:function(){
song = new Audio();
//speaKer = document.getElementById("imgSpeaker");
this.volume = 0.08;
this.isMute = false;
canPlayMP3 = (typeof song.canPlayType === "function" && song.canPlayType("audio/mpeg") !== "");
song.src = canPlayMP3 ? "http://rafih.co.il/wp-content/uploads/2013/07/1.mp3" : "http://rafih.co.il/wp-content/uploads/2013/07/1.ogg";
song.preload = 'auto';
},
/* start:function(){
song.src = canPlayMP3 ? "http://rafih.co.il/wp-content/uploads/2013/07/1.mp3" : "http://rafih.co.il/wp-content/uploads/2013/07/1.ogg";
song.volume = 0.08;
song.autoplay = true;
song.load();
},*/
play: function () {
song.volume = 0.08;
song.autoplay = true;
song.load();
// Music.speaker();
},
stop: function () {
if (!song.ended) {
song.pause();
}
},
next: function () {
if (curr < count) {
curr++;
}else curr = 1;
song.src = canPlayMP3 ? "http://rafih.co.il/wp-content/uploads/2013/07/" + curr + ".mp3" : "http://rafih.co.il/wp-content/uploads/2013/07/" + curr + ".ogg";
},
};
function load() {
Music.init();
}
You need to return false from the play buttons event handler, to prevent the page from scrolling to the top.
Change:
<div id="play" onclick='Music.play()'>
To:
<div id="play" onclick='Music.play(); return false;'>
That's because of the anchor in your link, such as href="#". A very simple fix would be to add return false; in to your inline handler attribute, such as onclick="Music.play(); return false;", however that isin't a good approach and is considered a bad practice.
Instead you could add your handlers programmatically, it will also make your code more modular and testable:
var Music = {
init: function (options) {
var playBtn = this.playBtn = document.querySelector(options.playBtn);
playBtn.addEventListener('click', this._onPlayBtnClick.bind(this));
//...
return this;
},
_onPlayBtnClick: function (e) {
e.preventDefault(); //prevents the browser's default behaviour
this.play();
},
//...
};
Then you could do something like:
function load() {
var musicController = Object.create(Music).init({
playBtn: '#play',
//...
});
}
You could also use it as a singleton like:
Music.init({ ... });
I have the following code snippet that controls an embedded youtube player. It works great on Chrome and Safari but not on Firefox.
jsfiddle : http://jsfiddle.net/fuSSn/4/
Code from my app:
the iframe:
<div class="tubeframe" id="video-frame-155" style="">
<iframe title="YouTube video player" width="350" height="262" src="http://www.youtube.com/embed/hc5xkf9JqoE?HD=1;rel=0;showinfo=0;autohide=1" frameborder="0" allowfullscreen="" id="video-frame-155-frame"></iframe>
</div>
my javascript:
var source_tag = document.createElement("script");
var first_source_tag = document.getElementsByTagName("script")[0];
first_source_tag.parentNode.insertBefore(source_tag, first_source_tag);
// This function will be called when the API is fully loaded
function onYouTubeIframeAPIReady() {
YT_ready(true)
console.log("api loaded! yikes")
}
function getFrameID(id){
var elem = document.getElementById(id);
if (elem) {
if(/^iframe$/i.test(elem.tagName)) return id; //Frame, OK
// else: Look for frame
var elems = elem.getElementsByTagName("iframe");
if (!elems.length) return null; //No iframe found, FAILURE
for (var i=0; i<elems.length; i++) {
if (/^https?:\/\/(?:www\.)?youtube(?:-nocookie)?\.com(\/|$)/i.test(elems[i].src)) break;
}
elem = elems[i]; //The only, or the best iFrame
if (elem.id) return elem.id; //Existing ID, return it
// else: Create a new ID
do { //Keep postfixing `-frame` until the ID is unique
id += "-frame";
} while (document.getElementById(id));
elem.id = id;
return id;
}
// If no element, return null.
return null;
}
// Define YT_ready function.
var YT_ready = (function(){
var onReady_funcs = [], api_isReady = false;
return function(func, b_before){
if (func === true) {
api_isReady = true;
while(onReady_funcs.length > 0){
// Removes the first func from the array, and execute func
onReady_funcs.shift()();
}
}
else if(typeof func == "function") {
if (api_isReady) func();
else onReady_funcs[b_before?"unshift":"push"](func);
}
}
})();
var video = function ( videoid, frameid) {
var player;
var that;
var seconds;
var duration;
var stateChangeCallback;
var update_play = 0;
return {
setOnStateChangeCallback: function(callback) {
stateChangeCallback = callback;
},
getCurrentTime: function() {
return player.getCurrentTime();
},
getPlayer: function () {
return player;
},
getVideoFrameId: function () {
return "video-frame-" + videoid;
},
initVideo: function (second) {
console.log("initing")
that = this;
YT_ready(function(){
var frameID = getFrameID("video-frame-" + videoid);
console.log("creating player")
console.log(frameID)
if (frameID) { //If the frame exists
console.log("frame exists")
player = new YT.Player(frameID, {
events: {
"onStateChange": that.stateChange
}
});
console.log("Player Created!");
if (second) {
console.log(second)
setTimeout(function() { console.log("seek to"); player.seekTo(second, false); player.stopVideo()}, 1000);
}
}
});
},
stateChange: function (event) {
console.log("event.data = ", event.data);
switch(event.data) {
case YT.PlayerState.PLAYING:
{
if (stateChangeCallback)
stateChangeCallback("play", player.getCurrentTime(), player.getDuration());
onsole.log("play");
}
break;
case YT.PlayerState.PAUSED:
case YT.PlayerState.CUED:
case YT.PlayerState.ENDED:
{
if (stateChangeCallback)
stateChangeCallback("pause", player.getCurrentTime(), player.getDuration());
console.log("pause");
}
break;
}
},
pauseVideo: function () {
player.stopVideo();
console.log('player.stopVid()');
},
seekTo: function(second) {
player.seekTo(second, false);
}
};
};
function onStateChange(vid, action, second, total) {
if (Videos[vid]) {
console.log( (second / total) * 100);
}
};
$(document).ready(function () {
var Videos = {};
logger.info("heyyy")
var videoId=155;
//if (videoId) {
Videos[videoId] = video(videoId, 155);
console.log(Videos[155])
Videos[155].initVideo();
Videos[155].setOnStateChangeCallback(function(action, second, total) {
onStateChange(155, action, second, total);
});
//}
Videos[155].seekTo(1000, false);
onStateChange(155, "start", 0, 0);
});
I know that the required script tags are being added, I can test that from console. I also know that onYouTubePlayerAPIReady() is actually called. But I still receive errors like
TypeError: player.stopVideo is not a function
When I run the three lines that adds the source tag again from the web console on firefox, the api seems to load and everything starts working again.
I have been struggling with this for days and I really need help figuring out what might be wrong. If it helps my application is developed in ruby on rails but I don't think this is relevant information.
Thanks
There is no problem with the above code. My video was loaded in a bootstrap modal. Modal's hide property would make it invisible to firefox and firefox would not load the api at all. So I removed the modal hide class and instead of display:none I used item.css("visibility", "visible"); and item.css("visibility", "hidden"); which made firefox load the api.
I made a quick audio player that has multiple instances. When you click to play, the playing var is set to true. If one would click on a different instance of .playAudio, I'm trying to set the lastPlayed instance to false.
I have a portion where I commented out the part I can't figure out.
JQUERY:
var lastPlay
var lastSelected
$('.playAudio').each(function(){
var audio = $(this).find('audio').get(0);
var playing = false
$(this).hover(function() {
if (playing) {
$(this).css({backgroundPosition: '-60px -60px'})
} else {
$(this).css({backgroundPosition: '0px -60px'})
}
},function() {
if (playing) {
$(this).css({backgroundPosition: '-60px 0'})
} else {
$(this).css({backgroundPosition: ''})
}
});
$(this).click(function(){
if (playing) {
playing = false
$(this).css({backgroundPosition: '0 60px'})
audio.currentTime = 0
audio.pause()
} else {
if (lastPlay) {
//** I'm trying to change the lastSelected's "playing" to false
lastPlay.pause()
}
playing = true
$(this).css({backgroundPosition: '-60px -60px'})
audio.play()
lastPlay = audio
lastSelected = $(this)
}
})
})
Here's one way to do it:
var lastPlay,
lastSelected,
Audios = [];
$('.playAudio').each(function(i){
var Audio = {};
Audios[i] = Audio;
Audio.audio = $(this).find('audio').get(0);
Audio.playing = false;
$(this).hover(function() {
if (Audio.playing) {
$(this).css({backgroundPosition: '-60px -60px'});
} else {
$(this).css({backgroundPosition: '0px -60px'});
}
},function() {
if (Audio.playing) {
$(this).css({backgroundPosition: '-60px 0'});
} else {
$(this).css({backgroundPosition: ''});
}
});
$(this).click(function(){
if (Audio.playing) {
Audio.playing = false;
$(this).css({backgroundPosition: '0 60px'});
Audio.audio.currentTime = 0;
Audio.audio.pause();
} else {
if (lastPlay && Audios[lastPlay]) {
Audios[lastPlay].audio.pause();
Audios[lastPlay].playing = false;
}
Audio.playing = true;
$(this).css({backgroundPosition: '-60px -60px'});
Audio.audio.play();
lastPlay = i;
lastSelected = $(this);
}
});
});
I've changed your script in a few ways:
I'm capturing the first parameter that jQuery passes into .each and using it as Unique Identifier between Audio Players
For each audio player the <audio> element, and it's playing state are being kept in the local Object Audio
I store a reference to each Audio Object as an array element in the global array Audios; using the unique identifier as the index
lastPlay now only holds the unique identifier of the last played audio element; I use it to access the appropriate Object in the Audios array, and set the relavent playing when necessary.