SoundManager reset SoundCloud playlist onfinish - javascript

This is my interpretation of a custom Soundcloud player using JavaScript SDK. I would like to reset playlist after last track is finished, which is partially acheved - 1st track is properly set, but my counter variable for next/prev buttons doesn't update.
Or maybe there is a better way to loop through the playlist than having a counter variable?
var autoplay = false;
$(document).ready(function() {
SC.get( '/resolve', {url: 'https://soundcloud.com/rockcurrent/sets/rc-playlist-new-rock-releases'}, function(pl) {
var i = 0;
var track_url = pl.tracks[i].uri;
var stream_sound = function(i) {
track_url = pl.tracks[i].uri;
SC.stream(track_url, function(sound) {
var new_play = function() {
sound.play({
onplay: function() {
title(i);
},
whileplaying: function() {
loader(this.position, this.duration);
},
onfinish: function() {
if (i < pl.tracks.length -1) {
i++;
autoplay = true;
}
else {
i = 0;
}
stream_sound(i);
}
});
}
new_play();
sound.pause();
if (autoplay) {
sound.resume();
is_playing = true;
}
autoplay = false;
$('#play').on('click', function() {
togglePause();
});
});
}
stream_sound(i);
$('#next').on('click', function() {
soundManager.stopAll();
if (i < pl.tracks.length -1) {
i++;
}
autoplay = true;
stream_sound(i);
});
$('#prev').on('click', function() {
soundManager.stopAll();
if (i > 0) {
i--;
}
autoplay = true;
stream_sound(i);
});
});
});

Related

Semplice (Wordpress) Javascript only working on page reload

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>

Play an audio file in Javascript

I'm trying to play an audio file in js. what am i doing wrong?
The script auto-stops after some events which is working 100%, now all I want to do is add a sound after it stops
Here is the code in:
function stop() {
stop_flag = true;
var audio = new Audio('play.mp3');
audio.play();
}
Here is the complete script.js the function is at the bottom.
chrome.runtime.onMessage.addListener(function(message) {
if (message.action == "init") {
init(message.options.divider, message.options.delay, message.options.maxLosses);
}
if (message.action == "stop") {
stop();
}
});
var stop_flag;
function init(divider, delay, maxLosses) {
var $table = $('table.dice_table').last();
var lastBetNumber;
var lastBetValue;
var lastProfit;
var losses = 0;
stop_flag = false;
loop_start();
function loop_start() {
lastBetNumber = getLastBetNumber();
var betValue = (getCurrentBalance() / divider).toFixed(9);
//var betValue = (getCurrentBalance() / divider);
lastBetValue = betValue;
$("input.bet").val(betValue);
play();
setTimeout(loop, delay);
}
function loop() {
if (stop_flag)
return;
waitForTableChange()
.then(roll)
.catch(loop_start);
function roll() {
//only if the last bet has changed \/
lastBetNumber = getLastBetNumber();
lastProfit = $table.children('tbody').children('tr').first().children('td').last().text()[0];
changeBet();
if (losses >= maxLosses)
return;
play();
setTimeout(loop, delay);
}
}
function waitForTableChange() {
return new Promise(function(resolve, reject) {
var n = 0;
attempt();
function attempt() {
n++;
if (n >= 100) {
reject();
return;
}
if (getLastBetNumber() == lastBetNumber) {
setTimeout(attempt, 100);
return;
}
resolve();
}
});
}
function changeBet() {
var newBetValue;
if (lastProfit == "-") {
losses++;
newBetValue = lastBetValue * 2;
} else {
losses = 0;
newBetValue = (getCurrentBalance() / divider).toFixed(9);
}
lastBetValue = newBetValue;
$("input.bet").val(newBetValue);
}
function play() {
$('input.clDicePlay').first()[0].click();
}
function getLastBetNumber() {
return $table.children('tbody').children('tr').first().children('td').first().text();
}
function getCurrentBalance() {
return $('.dice_select .chosen-single span').text().split('- ')[1].split(' ')[0];
}
}
function stop() {
var audio = new Audio('play.mp3');
stop_flag = true;
audio.play();
}
The problem is you are setting audio within the function stop(), which makes it local to that function. Once a function has been executed, all local vars are destroyed. You need to use the global scope to keep the object alive.
For example:
// set 'audio' in the global scope
var audio = new Audio('/path/to/default.mp3');
// create a play / pause button
function playPause(e) {
// NOTE: audio is from the gloabl scope
if (this.textContent == 'Play') {
audio.play();
this.textContent = 'Pause';
} else {
audio.pause();
this.textContent = 'Play';
}
}
window.onload = function() {
var a = document.getElementById('func');
a.addEventListener('click',playPause,false);
}
<button id="func">Play</button>

Javascript function executes twice, Meteor js

This is a simple script for horizontal fortune roulette, created using slick slider. Problem: function rollout() executed twice (and all helpers too) because template rendered twice. I'm using iron:router for routing, code:
Router.configure({
loadingTemplate: "loading",
layoutTemplate: "layout"
});
Router.map(function() {
this.route("hello", {
path: "/",
waitOn: function() {
return Meteor.subscribe("games");
}
});
});
hello.js:
Session.setDefault('currentSlide', 0);
Template.hello.events({
'click .create': function(e) {
e.preventDefault();
var ins = {
gameStartTime: new Date(),
finished: false
}
Games.insert({
gameStartTime: new Date(),
finished: "false"
});
Session.set("gameStatus", "waiting");
}
})
Template.hello.helpers({
currentSlide: function() {
var value = Session.get('currentSlide');
if (value === 25) {
return 0;
}
return value;
},
games: function() {
var game = Games.find();
return game;
},
gameHandler: function() {
var game = Games.findOne();
var gameStatus = Session.get("gameStatus");
if (game && game.finished === "false" && gameStatus === "waiting") {
Games.update({_id: game._id}, {
$set: {running: true}
});
} else if (gameStatus === "finished") {
Meteor.call('updateGame', game._id); //remove item from collection after game over; Error here: TypeError: Cannot read property '_id' of undefined;
console.log('game finished');
}
if (game && game.running === true) {
//Set Session variable and launch roulette
Session.set("gameStatus", "running");
rollout(game._id);
}
}
});
var rollout = function(gameid) {
Session.set("gameStatus", "running");
//make div's visible. They are have display:none by default.
document.getElementById("roulette").style.display = "block";
document.getElementById("result").style.display = "block";
document.getElementById("wrapper").style.display = "none";
var speed = 500; //default slider speed
Session.setDefault('speed', speed);
var r = $('#roulette').slick({
centerMode: true,
slidesToShow: 7,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 0,
speed: speed,
draggable: false,
pauseOnHover: false,
cssEase:'linear'
});
var maximum = 14;
var minimum = 0;
var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
var winResult = randomnumber;
var speed = 80;
var currentSlide = Session.get('currentSlide');
function roll(callback) {
Session.set('currentSlide', r.slickCurrentSlide());
if (speed < 800) {
speed += 20;
r.slickSetOption("speed", speed, false);
setTimeout(function() {
roll(callback);
}, 500);
} else if (speed >= 600 && speed < 1300) {
speed += 40;
r.slickSetOption("speed", speed, false);
setTimeout(function() {
roll(callback);
}, 300);
} else if (speed >= 1300 && speed < 20000) {
setTimeout(function() {
speed += 3;
r.slickSetOption('speed', speed, false);
if (Session.get('currentSlide') === winResult) {
r.slickPause();
setTimeout(function() {
//hide roulette div's
document.getElementById("roulette").style.display = "none";
document.getElementById("result").style.display = "none";
document.getElementById("wrapper").style.display = "block";
r.unslick();
Session.set('currentSlide', 0);
Session.set("gameStatus", "finished");
callback(true);
return
}, 10000);
} else {
roll(callback);
}
}, 30)
} else {
callback(true);
}
}
roll(function(callback) {
Meteor.call('updateGame', gameid); //remove item from collection
Session.set("gameStatus", "finished");
});
}
In template i'm using spinner by sacha:spin package and it working fine.
The gameHandler function should not be in your template helpers, which are only meant to supply information to the template. Instead, that logic needs to be moved to an autorun function. This autorun statement will re-run anytime a reactive datasource within it changes.
ex:
Template.hello.onCreated(function() {
this.autorun(function() {
var game = Games.findOne();
var gameStatus = Session.get("gameStatus");
// ...etc
});
}

Extend timeout function when button is clicked

This piece of code works, but I am trying to get the timeout function to reset to '0' every time the button is clicked.
var running = false,
count = 0,
run_for = 700;
var end_counter = function() {
if (running) {
running = false;
$("#status").text("Not Running");
alert(count);
started_at = 0;
}
};
$('button').click(function() {
if (running) {
count++;
} else {
running = true;
$("#status").text("Running");
count = 1;
setTimeout(end_counter, run_for);
}
});
Just cancel and restart it:
var timerId,
count = 0;
function end_counter() {
$("#status").text("Not Running");
alert(count);
count = 0;
}
$('button').click(function() {
$("#status").text("Running");
count++;
clearTimeout(timerId);
timerId = setTimeout(end_counter, 700);
});
var running = false,
count = 0,
run_for = 700;
var timer;
var end_counter = function() {
if (running) {
running = false;
$("#status").text("Not Running");
alert(count);
started_at = 0;
}
};
$('button').click(function() {
clearTimeout(timer);
if (running) {
count++;
timer = setTimeout(end_counter, run_for);
} else {
running = true;
$("#status").text("Running");
count = 1;
timer = setTimeout(end_counter, run_for);
}
});
Set timer to a variable - then clear it on click and restart it after count.

Jquery code works, javascript does not, what am i doing wrong?

Below is some code that has no jquery, but it is not working:
function start() {
var img = 0,
pic = ['nature', 'grass', 'earth', 'fall2', 'waterfall'],
slider = document.getElementsByClassName('slide_img'),
timerID = 0,
delay = 4000;
function back() {
img--;
if (img <= 0) {
img = pic.length - 1;
}
slider.src = 'pictures/' + pic[img] + '.jpg';
}
function go() {
img++;
if (img >= pic.length) {
img = 0;
}
slider.src = 'pictures/' + pic[img] + '.jpg';
}
document.getElementById('back').onclick = function() {
back();
}
document.getElementById('go').onclick = function() {
go();
}
slider.onmouseenter = function() {
clearTimeout(timerID);
}
document.getElementById('go').onmouseenter = function() {
clearTimeout(timerID);
}
document.getElementById('back').onmouseenter = function() {
clearTimeout(timerID);
}
slider.onmouseleave = function() {
clearTimeout(timerID);
auto();
}
function auto() {
timerID = setTimeout(function () {
go();
auto();
}, delay);
}
auto();
}
Here is what it is in jquery, this one works:
$('document').ready(function() {
var img = 0,
pic = ['nature', 'grass', 'earth', 'fall2', 'waterfall'],
slider = $('img.slide_img'),
timerID = 0,
delay = 4000;
function back() {
img--;
if (img <= 0) {
img = pic.length - 1;
}
slider.attr('src', 'pictures/' + pic[img] + '.jpg');
}
function go() {
img++;
if (img >= pic.length) {
img = 0;
}
slider.attr('src', 'pictures/' + pic[img] + '.jpg');
}
$('button#back').on('click', function() {
back();
});
$('button#go').on('click', function() {
go();
});
$(slider).on('mouseenter', function () {
clearTimeout(timerID);
});
$('button#go').on('mouseenter', function () {
clearTimeout(timerID);
});
$('button#back').on('mouseenter', function () {
clearTimeout(timerID);
});
$(slider).on('mouseleave', function () {
clearTimeout(timerID);
auto();
});
function auto() {
timerID = setTimeout(function () {
go();
auto();
}, delay);
}
auto();
});
What am i doing wrong, why is the first one not working. Im am trying to get rid of jquery so i dont have to include the source file.
You are not executing onload
try
var img = 0,
pic = ['nature', 'grass', 'earth', 'fall2', 'waterfall'],
slider,
timerID = 0,
delay = 4000;
window.onload=function() {
slider = document.getElementsByClassName('slide_img');
document.getElementById('back').onclick = function() {
back();
}
document.getElementById('go').onclick = function() {
go();
}
slider.onmouseover = function() {
clearTimeout(timerID);
}
document.getElementById('go').onmouseover = function() {
clearTimeout(timerID);
}
document.getElementById('back').onmouseover = function() {
clearTimeout(timerID);
}
slider.onmouseout = function() {
clearTimeout(timerID);
auto();
}
auto();
}
function auto() {
timerID = setTimeout(function () {
go();
auto();
}, delay);
}
function back() {
img--;
if (img <= 0) {
img = pic.length - 1;
}
slider.src = 'pictures/' + pic[img] + '.jpg';
}
function go() {
img++;
if (img >= pic.length) {
img = 0;
}
slider.src = 'pictures/' + pic[img] + '.jpg';
}
Use "onmouseover" and onmouseout" for canonical events:
slider.onmouseover = function() {
clearTimeout(timerID);
}
document.getElementById('go').onmouseover = function() {
clearTimeout(timerID);
}
document.getElementById('back').onmouseover = function() {
clearTimeout(timerID);
}
slider.onmouseout = function() {
clearTimeout(timerID);
auto();
}
And don't forget to define "slider" (the initial part is missing in your script):
var slider = document.querySelector('img.slide_img');
<body onload="start"></body>
The JavaScript start doesn't do anything. If you want to call a function, then you need to follow it with ().
This is a rather obtrusive way to deal with event handler assignment though. It is generally preferred to assign such things with JavaScript:
addEventListener('load', start);
See MDN for compatibility notes.
However, you don't have anything in your code that depends on the entire document being loaded. So you can simply:
<script>
start();
</script>
</body>
at the end of your document.
(You can put the whole script there for that matter, and keep it in an external file).

Categories