How to pause streaming in soundcloud javascript api - javascript

I would like to allow a sound file to play and pause. The documentation shows how to play a streaming file:
$("#stream").live("click", function(){
SC.stream("/tracks/{'track-id'}", function(sound){
sound.play();
};
It uses Sound Manager to stream and uses some of it's objects and methods... like .pause()!
So here's the code i think should work:
var is_playing="false";
$("#stream").live("click", function(){
SC.stream("/tracks/{'track-id'}", function(sound){
if (is_playing==="true")
{
sound.pause();
is_playing = "false";
console.log(is_playing);
}
else if (is_playing === "false")
{
sound.play();
is_playing = "true";
console.log(is_playing);
}
});
However, it continues to play the track without pausing. Any ideas?
Thanks.

var is_playing = false;
soundManager.setup({
url: '/swf/soundmanager2.swf',
preferFlash: false,
onready: function() {
var mySound = soundManager.createSound({
id: 'aSound',
url: 'sonidos/sonido1.mp3' ,
autoplay: false
});
$("#stream").live("click", function(){
if (is_playing==false){
mySound.play();
is_playing = true;
}else if (is_playing== true) {
mySound.stop();
is_playing = false;
}
});
},
/* ontimeout: function() {
// Hrmm, SM2 could not start. Missing SWF? Flash blocked? Show an error, etc.?
}*/
});
</script>

You have to use sound.stop();
There is also a built in function to toggle play/pause of a sound.
Use sound.togglePause(); to do that.

SC.stream("/tracks/13680213", function(sound) {
SC.sound = sound;
});
This means you aren't writing event listeners inside your SC.stream constructor then you can access the following (and more) at will:
SC.sound.play();
SC.sound.pause();
SC.sound.stop();
SC.sound.pause();
SC.sound.playState;

Since there are very few answers on this subject, I thought I would answer my own question.
I went ahead and downloaded Sound Manager 2 and placed the necessary files where they needed to be (you can find this in the basic tutorials section of the sound manager2 page.)
http://www.schillmania.com/projects/soundmanager2/demo/template/
The trick wass to locate the SoundCloud mp3 associated with the user I wanted to embed. To do this, I had to use a RESTClient and enter the appropriate api url.
It looks like this.
http://api.soundcloud.com/tracks/12758186.json?client_id={MyClient_ID_number}
The http://api.soundcloud.com/tracks/ is a general pointer to the track id="12758186". This is followed by the JSONP inclusion of my personal client_id to validate my request to the soundcloud server.
Once I had this url, I tried it in my browser and it redirected me to ** another url ** with an HTML5 mp3 player, which automatically played the song.
I got the idea to do this from this soundcloud doc:
http://developers.soundcloud.com/docs#playing
I then copied this url and mashed the code from my original question to the basic tutorial mentioned above (http://www.schillmania.com/projects/soundmanager2/demo/template/).
Final Code:
var is_playing = false;
$("#stream").live("click", function(){
soundManager.setup({
url: './swf/soundmanager2.swf',
onready: function() {
var mySound = soundManager.createSound({
id: 'aSound',
url: {**another url**},
autoplay: false
});
if (is_playing===false)
{
mySound.play();
is_playing = true;
}
else if (is_playing=== true)
{
mySound.stop();
is_playing = false;
}
},
ontimeout: function() {
// Hrmm, SM2 could not start. Missing SWF? Flash blocked? Show an error, etc.?
}
});
});

Simply link the event which you would like to trigger the pause function to the "sound" object which is passed into SC.stream()'s callback function.
The form in the following code accepts a sound cloud link such as this one: https://soundcloud.com/djalmix-1/living-in-stereo-dj-almix (so paste that in to the form once the app is live and click load). Also you must provide your own client_id that soundcloud gives you when you register your app, this takes only a minute or so.
<!DOCTYPE html>
<html>
<head></head>
<body>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
function load_sound() {
var track_url = document.getElementById("sc_url").value;
SC.initialize({
client_id: 'client_id'
});
SC.get('/resolve', {url: track_url}, function(track) {
console.log("the track id is: " + track.id);
SC.stream("/tracks/" + track.id, function(sound) {
var is_playing = true;
sound.play();
document.getElementById("stream").onclick = function(){
if(is_playing === false){
sound.resume();
is_playing = true;
} else if(is_playing === true){
sound.pause();
is_playing = false;
}
};
});
});
}
</script>
<form>
<input id="sc_url" type="url">
<input type="button" onclick="load_sound();" value="load">
</form>
<button id="stream">pause/resume</button>
</body>
</html>

Related

Toggle Play/Pause Youtube Video with external button

I have a template I'm building out using fullPage js to create sliding sections. The page supports video, but scroll and gestures are disabled when users scroll with the cursor on top of the video itself. Likewise, this behavior is observed on mobile.
To work around this, I'm using an empty div overlaying the youtube iframe. This solves the scrolling behavior, but I also lack the ability to directly control the youtube player. I've tried using the youtube API and jquery to fake being able to toggle play/pause with the empty div I have on top of the youtube player, but it's not working.
http://codepen.io/lumpeter/pen/XpayeB
The primary code for youtube is:
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById("player");
ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
}
function onPlayerReady(event) {
$('#video-button').click(function(event){
ytplayer.playVideo();
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
$('#video-button').click(function(event){
ytplayer.pauseVideo();
});
}
else {
$('#video-button').click(function(event){
ytplayer.playVideo();
});
}
}
Can anybody tell why this isn't working? I have event listeners looking for changes and using a boolean to detect the state of the video to toggle play/pause, but for some reason this doesn't work like I anticipated.
===============UPDATE=================
I've also tried the following:
$(document).on('click', '#pauseVideo', function(){
player = new YT.Player('myVideo')
if (event.data == player.PlayerState.PAUSED) {
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}','*');
}
if (event.data == player.PlayerState.PLAYING) {
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');
}
});
However, I get the error "Uncaught ReferenceError: YT is not defined."
As fullpage.js already does part of the job by adding ?enablejsapi=1 and loading the JS script of the API for you, then you only have to do this:
var player;
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('myVideo');
}
$(document).on('click', '#pauseVideo', function(){
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');
});
Reproduction online
Thanks Alvaro! Yeah I was overthinking the solution a bit with the youtube api. I just needed to use a boolean with a binary true/false statement. Super easy, should have seen it before. Again thanks for your help!
var player;
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('myVideo',{
events: { 'onStateChange': onPlayerStateChange }
});
}
var isPlaying = true;
$(document).on('click', '#pauseVideo', function(){
if ( isPlaying == true){
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');
isPlaying = false;
} else {
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}','*');
isPlaying = true;
}
});

JavaScript play sound when user/tab/browser is inactive

I am using the following code to play sound when user receives a message AND the user is not in the tab mean that the current tab is INACTIVE or user is outside current tab.
$(window).hover(function(event) {
if (event.fromElement) {
console.log("inactive");
} else {
console.log("active");
beep("beep.wav", 1.0); //your code here
}
});
I want to play the sound only when user is away from tab and NOT when he is inside the tab. Right now the sound only plays when the user comes back to the tab. This is not what i want.
I can see facebook and gmail does this even if user is outside in another tab, How do they do it?
I searched on SO but couldn't find any answer for this!
Help me!
I imagine something like:
var intervalHandler = null;
$(window).blur(function(e) {
intervalHandler = window.setInterval(function() {
document.getElementById('beep').play();
window.clearInterval(intervalHandler);
}, 1000);
});
$(window).focus(function(e) {
window.clearInterval(intervalHandler);
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<audio id="beep" src="http://www.soundjay.com/button/beep-07.wav" autostart="false" ></audio>
Found from SO myself:
They disable the sound when user tab is active:
var isactive = false;
function playSound(){
if (isactive) return;
playWav...;
}
onNotificaitonComes = playSound;
$(window).focus(function(){
isactive = true;
}).blur(function(){
isactive = false;
});

Running a HTML5 Audio player in a Firefox Add-ons SDK page-worker

I am trying to repair a firefox addon that I created some time ago which has stopped functioning properly after a recent-ish Firefox update. The part which no longer functions was a mp3 player, which ran in the background.
The page-worker has a very small html page with an embedded media player and a script that controls the player. The script is passed in a filepath for an mp3 on my machine to use as the players src, and then told to start playing. This used to work, but now upon calling the embedded player's play function an error is thrown. The src is correctly set and the play event triggers, but the canplay event does not. The error code given is 4, which I believe is MEDIA_ERR_SRC_NOT_SUPPORTED.
If I open the HTML page and feed the player the filepath manually, it all works fine. What's going wrong here that wasn't before?
The HTML page is
<!DOCTYPE hmtl>
<html>
<head>
<title>Sound Stone: mp3 pageworker</title>
</head>
<body>
<video></video>
</body>
<html>
The content script is
var player = document.getElementsByTagName("video")[0];
var starttime;
var stoptime;
var checkTime;
self.port.on("start", function(url){
player.src=url;
player.pause();
stoptime = undefined;
self.port.emit("change", false);
});
self.port.on("stop", function(){
player.pause();
player.removeEventListener("canplay", goTo);
});
self.port.on("play", function(beg, end){
clearInterval(checkTime);
if(beg){
starttime = beg/1000;
}
if(end){
stoptime = end/1000;
}
player.play(); // this is where it goes wrong
if(beg){
player.addEventListener("canplay", goTo);
}
if(stoptime){
checkTime = setInterval(function (){
if(player.currentTime>=stoptime){
player.currentTime=99999;
clearInterval(checkTime);
}
}, 1000);
}
});
self.port.on("pause", function(){
player.pause();
});
player.onplay = function(){
self.port.emit("change", true);
}
player.onpause = function(){
self.port.emit("change", false);
}
player.onended = function(){
self.port.emit("done");
}
player.onerror = function(){
self.port.emit("out", player.error.code); // this outputs 4
self.port.emit("out", player.src); // this outputs as expected
}
function goTo(){
player.currentTime=starttime;
player.removeEventListener("canplay", goTo);
}
And a small excerpt of the main program is
var mp3 = worker.Page({
contentScriptFile: "./mp3.js",
contentURL: "./mp3.html",
});
mp3.port.on("out", function(msg){
console.log(msg);
});

can i reproduce a video/flv radio station stream with javascript and flash?

i am trying the soundmanager http://www.schillmania.com/projects/soundmanager2/demo/api/ to play a radio online, but i am having some problems... i see in the console that i am getting the stream, but its never played...
Here my sample code:
var fortyeight = soundManager.createSound({
url: 'http://stream.timlradio.co.uk/ABSOLUTECRIRAACS?type=.flv'
});
if (!fortyeight.loaded) {
// first time loading/playing
fortyeight.load({
stream: false,
onload: function() {
// sound has fully-loaded
this.play();
}
});
} else {
// sound has already loaded
fortyeight.play();
}
Any clues?

HTML5 Audio does not play more than once

this does not work for me! anyone having the same issue? my code seems straightforward but it only plays once I need to be able to play over and over. see as follows:
My Html:
<audio id="siren" src="sounds/400.ogg" preload="auto">
and my JS:
function play_siren() {
log("play sound");
if(document.getElementById('siren').paused == true){
document.getElementById('siren').play();
}
}
function pause_siren() {
try{
if(document.getElementById('siren').paused == false){
document.getElementById('siren').pause();
}
log("paused siren");
}catch(err){
log(err.message);
}
try{
if(document.getElementById('siren').currentTime > 0.0){
document.getElementById('siren').currentTime = 0.0;
}
log("reset siren");
}catch(err){
log(err.message);
}
}
it is started programmatically in the JS code as follows:
if(Obj[3].siren == true && isPlayingSiren == false){
play_siren();
isPlayingSiren = true;
}else if(Obj[3].siren == false && isPlayingSiren == true){
pause_siren();
isPlayingSiren = false;
}
I found this gentleman's code and his DOES seem to work: http://html5.komplett.cc/code/chap_video/js_audioPlayer_en.html
But setting "currentTime = 0" is not doing anything for me.
I can't figure it out. I tested with Chrome, Firefox and Safari. Firefox does not work at all so far Chrome seems to be the best for HTML5 but still I can only play once.
I even tried mp3 and ogg same behavior.
Please shed some light. Thank you!
here is full HTML:
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" media="all" href="js_audioPlayer.css">
<title>HTMLMediaElement example - Audio Player</title>
<script src="../js/audioPlayer.js"></script>
</head>
<body>
<fieldset>
<audio src="sounds/400.ogg" preload="auto"></audio>
<legend>Audio Player (400)</legend>
</fieldset>
<script>
function loadXMLDoc(){
_pause();
updateProgress(0);
playPause();
}
var loadXmlTimer = setInterval(loadXMLDoc, 2000);
</script>
</body>
</html>
and here is full javascript:
// global callback functions
var playPause, updateProgress, _play, _pause;
/* initialize audio player */
window.onload = function() {
// keep track of playback status
var AudioStatus = {
isPlaying : false
};
// define references to audio, pulldown menu, play-button, slider and time display
var audio = document.querySelector("AUDIO");
/* load track by menu-index */
var loadTrack = function(idx) {
audio.src = '../sounds/400.ogg';
audio.load();
};
/* callback to play or pause */
_play = function() {
audio.play();
log("play");
AudioStatus.isPlaying = true;
};
_pause = function() {
audio.pause();
log("pause");
AudioStatus.isPlaying = false;
};
playPause = function() {
if (audio.paused) {
_play();
}
else {
_pause();
}
};
/* callback to set or update playback position */
updateProgress = function(value) {
audio.currentTime = value;
log("updateProgress");
};
};
the timer plays the sounds programmatically on the expiration. this works as long it is private. I did not understand why it has to be private.
Does it pass thru the if statement?
You could use ontimeupdate for placing the value of document.getElementById('siren').currentTime in a variable.
If set to more than 0, then you could update it in an if conditionnal.
All of the previous solutions are unacceptable because they download the same sound file for each time the sound is played! Do this instead, for the sake of simplicity and efficiency:
var sound = document.getElementById("mySound")
if(window.chrome){
sound = sound.cloneNode()
}
sound.play()
This is how I fixed the problem with chrome specifically.

Categories