Play SoundCloud stream uri in HTML 5 mp3 player (audio.js) - javascript

I would like to load tracks from SoundCloud and have them played in a HTML5 audio player provided by: http://kolber.github.io/audiojs/
I have it working with .mp3 files, as they do in the demo. I have also successfully connected to the SoundCloud api and placed the src in the right place. However the stream uri : api.soundcloud .com/tracks/75868018/stream?client_id=ed34fc3159859e080af9eb55f8c3bb16 (it's a fake client id, I can't post link) does not work.
I have tried using both
sound.stream_url & sound.uri detailed here: developers.soundcloud .com (cannot post link)
How do I play a stream link from the Soundcloud api in an mp3 player?
Below is my code
HTML - Stripped
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script> // load jquery
<script src="http://connect.soundcloud.com/sdk.js"></script> // connect to soundlcoud
<script src="jb3.js" type="text/javascript"></script> // run script to load track into <li> element in DOM
<script src="audio.min.js"></script> // load audio,js script for audio player
</head>
<body>
<audio ></audio>
<h2>Playlist</h2>
<ol id="userPlaylist">
<li>dead wrong intro</li> //woorking track using .mp3
<li class="playing">
<a data-src="http://api.soundcloud.com/tracks/75868018/stream?client_id=ed34fc3159859e080af9eb55f8c3bb16" href="#">sc SONG</a>
</li>
//STREAM THAT IS NOT WORKING
</body>
</html>
MY JAVASCRIPT - jb3.js
function addSc() {
SC.get("/tracks/75868018", {}, function(sound){
alert("Sound URI: "+sound.uri);
$("ol#userPlaylist").append('<li> <a href="#" data-src="'+sound.stream_url+'.json/stream?client_id=ed34fc3159859e080af9eb8558c3bb16">sc SONG</li>');
});
}
window.onload = function() {
SC.initialize({
client_id: 'ed34fc3159859e080af9eb55f8c3bb16'
});
addSc();
};

I have tested it with the default player and demos/test6.html with sc-urls, and it works fine.
Where do you create the player?
Looks like your url seems to be wrong (pls check Ex 2 below)
EXAMPLE 1
HTML
<audio src="http://api.soundcloud.com/tracks/148976759/stream?client_id=201b55a1a16e7c0a122d112590b32e4a" preload="auto"></audio>
JS
audiojs.events.ready(function() {
audiojs.createAll();
});
http://jsfiddle.net/iambnz/6dKLy/
EXAMPLE 2 with playlist (test6 just with sc urls)
HTML
<div id="wrapper">
<h1>Test .. :-) <em>(2014)</em></h1>
<audio preload></audio>
<ol>
<li>Phil Collins Edit</li>
<li>Your track</li>
</ol>
</div>
JS
$(function() {
// Setup the player to autoplay the next track
var a = audiojs.createAll({
trackEnded: function() {
var next = $('ol li.playing').next();
if (!next.length) next = $('ol li').first();
next.addClass('playing').siblings().removeClass('playing');
audio.load($('a', next).attr('data-src'));
audio.play();
}
});
// Load in the first track
var audio = a[0];
first = $('ol a').attr('data-src');
$('ol li').first().addClass('playing');
audio.load(first);
// Load in a track on click
$('ol li').click(function(e) {
e.preventDefault();
$(this).addClass('playing').siblings().removeClass('playing');
audio.load($('a', this).attr('data-src'));
audio.play();
});
// Keyboard shortcuts
$(document).keydown(function(e) {
var unicode = e.charCode ? e.charCode : e.keyCode;
// right arrow
if (unicode == 39) {
var next = $('li.playing').next();
if (!next.length) next = $('ol li').first();
next.click();
// back arrow
} else if (unicode == 37) {
var prev = $('li.playing').prev();
if (!prev.length) prev = $('ol li').last();
prev.click();
// spacebar
} else if (unicode == 32) {
audio.playPause();
}
})
});
http://jsfiddle.net/iambnz/VL7n8/
Check: http://kolber.github.io/audiojs/demos/test6.html

Related

Embedded Vimeo Videos to Play Automatically

with my code below, I play videos one after the other but the videos are stored locally and I would like to use integrated vimeo videos on a page and have them start playing as soon as the page is open and when the first video has finished, the second one starts.
in my code i have an array (playlist[]) of src ... is it possible to replace the source with the source of my Vimeo videos or no?
<video id="headervideo" class="video">
<source id="videoFile" width="100%" height="100%" />
Your browser does not support the video tag.
</video>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript">
//==============================
var track = 0
var playlist = [{src: 'https://player.vimeo.com/video/240512614?title=0&byline=0&portrait=0&badge=0', type: 'video/mp4'}, {src: 'https://player.vimeo.com/video/240289181', type: 'video/mp4'}]
//==============================
$(document).ready(function() {
document.getElementById('headervideo').addEventListener('ended', function () {
track++
track = (track > (playlist.length - 1)) ? 0 : track
//alert(track)
playMovie(playlist[track])
}, false)
playMovie(playlist[track])
})
//==============================
playMovie = function (movie) {
$('#videoFile')
.prop('src', movie.src)
.prop('type', movie.type)
document.getElementById('headervideo').load()
document.getElementById('headervideo').play()
}
//==============================
</script>
Maybe this can help you, according to vimeo documentation
EDIT
I replace the code posted before with a working example
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="video-container"></div>
<script src="https://player.vimeo.com/api/player.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var videos = ['59777392', '19231868', '202791609']; //videos ids
var options = {
width: 640
};
playMovie(null, videos, options)
})
var playMovie = function(player, videos, options) {
if (!videos.length) {
return false;
}
var video = videos.shift();
if(!player){
options.id = video;
player = new Vimeo.Player('video-container', options);
player.play();
player.on('ended', function(){
playMovie(player, videos, options)
})
}else{
player.loadVideo(video)
.then(function(){
player.play();
})
.catch(function(error) {
console.warn(error);
});
}
}
</script>
</body>
</html>
I tested firstly with autoplay in the options but it starts automatically only the first two videos. I solved the problem by calling the play function on each video

Click in icon play to start sound, then click stop icon to stop sound

I have a link with icon play, when I click in this icon I want to start play a sound. And in the moment that the sound starts I want to show a stop icon replacing the play icon.
I am trying to do this with this code below, but isn´t working:
jquery:
$(function(){
function play() {
var audio = document.getElementById('audio1');
if (audio.paused) {
audio.play();
}else{
audio.pause();
audio.currentTime = 0
}
}
});
is this what you need?
I made a fiddle: http://jsfiddle.net/boqs38pf/
HTML:
<audio id="audio1" src="http://www.freesfx.co.uk/rx2/mp3s/10/11771_1410942915.mp3"></audio>
<a id="play" href="#" onClick="play()"><i class="fa fa-play"></i></a>
<a id="stop" href="#" onClick="play()"><i class="fa fa-stop"></i></a>
Jquery:
$(document).ready(function() {
var audioElement = document.getElementById('audio1');
$('#stop').hide();
$('#play').click(function() {
$('#play').hide();
$('#stop').show();
audioElement.play();
});
$('#stop').click(function() {
$('#play').show();
$('#stop').hide();
audioElement.pause();
});
});
To make it more dynamic for multiple audio files what you would want to do is assign each button an id with a number that would match the id of the song you want it to control. After that you need to add to the .click function some code that will get the id of the button clicked and and play the song with the relevant Id.
$('.play').click(function(){
var i = $(this).attr('id');
var c = parseInt(i);
var g = '#idofsong' + c;
g.play();
});
Edit: here is a working fiddle
Also you want to use var c = i.replace(/[A-Za-z$-]/g, ""); instead of parseInt if the id contains letters

audio.play() html tag doesn't play in chrome

I am facing an issue while playing audio in chrome when audio.src is not called preceeding to play call. However, firefox plays it alright. Can someone pls suggest? Below is the fiddle link -
http://jsfiddle.net/vn215r2d/1/
One can also find the code over here -
<html>
<head>
<script language="javascript">
var audioo = document.createElement("audio");
function newCall() {
audioo.src = "";
audioo.src = "http://xx.xx.xx.xx:8181/api/captcha/sound";
audioo.play();
}
function playAgain() {
audioo.play(); // doesn't work in chrome :(
}
</script>
</head>
<body>
<button type="button" onClick="newCall()">New Captcha Call</button>
<br>
<button type="button" onClick="playAgain()">Replay Captcha</button>
</body>
</html>
Update
Oh waw, apparently is comes down to the audio.currentTime not being writeable until you rewrite the src. Heres what you can do and it does work:
function newCall() {
audioo.src = "http://xx.xx.xx.xx:8181/api/captcha/sound";
// make all audio attributes writeable again by resetting the src
audioo.src = audio.src;
}
The answer took a bit of googling, but I got it from here: https://stackoverflow.com/a/14850353
Original
I tested on Chrome with resetting the audio position and it worked. Its safest to pause first, but it works either way.
var audioo = document.createElement("audio");
// Lets add an event listener to play when we are ready to start playing
audioo.addEventListener("canplaythrough", function(){
audioo.play();
}, false);
function newCall() {
audioo.src = "";
audioo.src = "http://xx.xx.xx.xx:8181/api/captcha/sound";
}
function playAgain() {
// Let's check if we are ready enough to play
if(audioo.readyState === 4){
audioo.pause(); // first pause
audioo.currentTime = 0; // then reset
audioo.play(); // then play
} else {
// else inform us that we are not ready to play yet.
alert("Audio not ready yet.");
}
}
Here are two fun resources that can help:
MDN:
MediaElement (usefull properties and functions)
MDN:
Media Events (for event listeners)

Can I start playing another video after the original video finished? (Vimeo)

Hy,
I need to develeop a site, that will embed videos from Vimeo.
If I use VimeoAPI, can Ilisten when the video is finished? And if it finished, can I start another video from Vimeo?
Thanks, Dave.
Assuming that you have used the code provided in the Vimeo Api page you should be using the following to show an initial video:
<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="custom.js" ></script>
</head>
<body>
<iframe id="vimeoplayer"
src="//player.vimeo.com/video/76979871?api=1&player_id=vimeoplayer"
width="100%" height="100%" webkitallowfullscreen mozallowfullscreen
allowfullscreen ></iframe>
<div>
<button>Play</button>
<button>Stop</button>
<p>Status: <span class="status">…</span></p>
</div>
</body>
</html>
Make sure that the iframe ID is the same with the "player_id".
Then in your custom.js file use the code from the Vimeo API page:
$(function() {
var player = $('#vimeoplayer');
var url = window.location.protocol + player.attr('src').split('?')[0];
var status = $('.status');
// Listen for messages from the player
if (window.addEventListener){
window.addEventListener('message', onMessageReceived, false);
}
else {
window.attachEvent('onmessage', onMessageReceived, false);
}
// Handle messages received from the player
function onMessageReceived(e) {
var data = JSON.parse(e.data);
switch (data.event) {
case 'ready':
onReady();
break;
case 'playProgress':
onPlayProgress(data.data);
break;
case 'pause':
onPause();
break;
case 'finish':
onFinish();
break;
}
}
// Call the API when a button is pressed
$('button').on('click', function() {
post($(this).text().toLowerCase());
});
// Helper function for sending a message to the player
function post(action, value) {
var data = {
method: action
};
if (value) {
data.value = value;
}
var message = JSON.stringify(data);
player[0].contentWindow.postMessage(data, url);
}
function onReady() {
status.text('ready');
post('addEventListener', 'pause');
post('addEventListener', 'finish');
post('addEventListener', 'playProgress');
}
function onPause() {
status.text('paused');
}
// when the video is finished
function onFinish() {
status.text('finished');
// load the next video
document.getElementById('vimeoplayer').src = "//player.vimeo.com/video/104990881?api=1&player_id=vimeovideo";
}
function onPlayProgress(data) {
status.text(data.seconds + 's played');
}
});
The code that changes the video, once the first one is finished, is inside the onFinish() function. The code inside this function changes the iframe source (src) to the one of the next video that you want to play.
You could use alternative methods of displaying another video and the above method is a very basic one just to display the requested functionality.
I wrote a jQuery Vimeo plugin a few months ago. Using this plugin, the code would be something like:
$("#somevideo").on("finish", function(){
$("#anothervideo").vimeo("play");
});
Yes, check out the player API for information on how to be notified when a video is complete, and how to start new videos https://developer.vimeo.com/player/js-api

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