Soundcloud API: Playing correct sound - javascript

Context: This is a Soundcloud API javascript and iframe that plays the sound of the soundcloud link when you hover over the link. The link is inputted into a table just so you know.
Problem: The problem is that when I hover over a link that I input into the table i.e say I put multiple links (each connected to a different sound) in the table but when I hover over each link they only play the sound of the first link in the table; The other links in the table does not play their appropriate sounds. Can someone help me modify the code below to fix this issue? Provide the modified code integrated with the original code below.
HTML (Iframe the src is customized to play that particular link):
<div class="clickme">
<iframe id="sc-widget" width="300" height="200" allow="autoplay"
src="https://w.soundcloud.com/player/?url=https://soundcloud.com{{-list2[1]-}}&show_artwork=true"
frameborder="0" style="display: none">
</iframe>
</div>
Javascript(Soundcloud API):
<script src="https://w.soundcloud.com/player/api.js" type="text/javascript"></script>
<script type="text/javascript">
(function () {
var widgetIframe = document.getElementById('sc-widget'),
widget = SC.Widget(widgetIframe);
widget.bind(SC.Widget.Events.READY, function () {
widget.bind(SC.Widget.Events.PLAY, function () {
// get information about currently playing sound
console.log('sound is beginning to play');
});
// get current level of volume
widget.getVolume(function (volume) {
console.log('current volume value is ' + volume);
});
// set new volume level
widget.setVolume(50);
// get the value of the current position
widget.bind(SC.Widget.Events.FINISH, function () {
// get information about currently playing sound
console.log('replaying sound');
widget.seekTo(0);
widget.play();
});
});
// Shorthand for $( document ).ready()
// A $( document ).ready() block.
$(document).ready(function () {
console.log("ready!");
var menu = document.getElementsByClassName("clickme");
for (i = 0; i < menu.length; i++) {
var list = menu[i];
var link = String(list.outerHTML)
if (link.includes('soundcloud')) {
list.addEventListener("mouseenter", function (event) {
console.log('start soundcloud');
widget.play();
});
list.addEventListener("mouseleave", function (event) {
console.log('pause soundcloud ');
widget.pause();
});
}
}
});
}());
</script>

The problem is that you're hard-coding the soundcloud player to the first iframe with an id of sc-widget by the following lines:
var widgetIframe = document.getElementById('sc-widget'),
widget = SC.Widget(widgetIframe);
To be able to play a different track on hovering, the widget needs to be populated with the proper iframe.
So these are the steps needed. If a user hovers over one of the container divs
Check if the user already hovered this specific item.
In case he did, resume the sound.
In case he didn't unbind any events from the widget if there are any, initialize the widget with the iframe, bind the required events and start playback from the beginning.
If the user leaves a container div with the mouse, stop playback if there is something playing at all.
Here's a working example:
let widget;
let currentWidget;
$(document).ready(function() {
console.log("ready!");
var menu = document.getElementsByClassName("clickme");
for (i = 0; i < menu.length; i++) {
var list = menu[i];
var link = String(list.outerHTML);
if (link.includes('soundcloud')) {
list.addEventListener("mouseenter", function(event) {
if (event.currentTarget.childNodes[1] == currentWidget) {
widget.play();
} else {
if (widget) {
widget.unbind(SC.Widget.Events.PLAY);
widget.unbind(SC.Widget.Events.READY);
widget.unbind(SC.Widget.Events.FINISH);
}
widget = SC.Widget(event.currentTarget.childNodes[1]);
widget.bind(SC.Widget.Events.READY, function() {
widget.bind(SC.Widget.Events.PLAY, function() {
// get information about currently playing sound
console.log('sound is beginning to play');
});
// get current level of volume
widget.getVolume(function(volume) {
console.log('current volume value is ' + volume);
});
// set new volume level
widget.setVolume(50);
// get the value of the current position
widget.bind(SC.Widget.Events.FINISH, function() {
// get information about currently playing sound
console.log('replaying sound');
widget.seekTo(0);
widget.play();
});
});
widget.play();
}
currentWidget = event.currentTarget.childNodes[1];
});
list.addEventListener("mouseleave", function(event) {
console.log('pause soundcloud ');
if (widget) {
widget.pause();
}
});
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://w.soundcloud.com/player/api.js" type="text/javascript"></script>
<div class="clickme" style="width: fit-content;height: fit-content;">
<iframe width="300" height="200" allow="autoplay" src="https://w.soundcloud.com/player/?url=https://soundcloud.com/crythemindlesselectron/legend-of-zelda-ocarina-of-time-thunderstruck-oc-remix&show_artwork=true" frameborder="0">
</iframe>
</div>
<div class="clickme" style="width: fit-content;height: fit-content;">
<iframe width="300" height="200" allow="autoplay" src="https://w.soundcloud.com/player/?url=https://soundcloud.com/daniel-feldkamp-2/sets/oc-remix-zelda&show_artwork=true" frameborder="0">
</iframe>
</div>

Related

JavaScript: embedded YouTube video not playing in modal popup

I have the following code which looks at a specific css class .vma_iFramePopup and from it, takes the link stored in the src. And then loads that in a modal popup.
$(document).ready(function () {
$(".vma_overlay").click(function (event) {
var $videoSrcOriginal = $(event.target).siblings('.vma_iFramePopup').attr("src");
// Check if the embedded youtube url has any attributes appended
// by looking for a '?' in the url.
// If one is found, append our autoplay attribute using '&',
// else append it with '?'.
if ($videoSrcOriginal.indexOf('?') > -1) {
var $videoSrc = $videoSrcOriginal
// when the modal is opened autoplay it
$('#vma_ModalBox').on('shown.bs.modal', function (e) {
// set the video src to autoplay
var $videoSrcAuto = $videoSrc + "&autoplay=1&mute=1";
$("#vma_video").attr('src', $videoSrcAuto);
$('body').addClass("modalyt");
})
} else {
var $videoSrc = $(".vma_iFramePopup").attr("src");
// when the modal is opened autoplay it
$('#vma_ModalBox').on('shown.bs.modal', function (e) {
// set the video src to autoplay
var $videoSrcAuto = $videoSrc + "?autoplay=1&mute=1";
$("#vma_video").attr('src', $videoSrcAuto);
$('body').addClass("modalyt");
})
}
// stop playing the youtube video when modal is closed
$('#vma_ModalBox').on('hide.bs.modal', function (e) {
$("#vma_video").attr('src', $videoSrc);
$('body').removeClass("modalyt");
})
});
});
I was informed that the videos are not playing in the modal. The modal when loaded is empty.
When I check the browser console, I am not seeing any relevant errors.
When I check the iframe inside my modal popup I see that it says
src(unknown)
in the src element:
<iframe class="embed-responsive-item" width="80%" height="80%" src(unknown) id="vma_video" allowfullscreen="" data-gtm-yt-inspected-9256558_25="true">></iframe>
I have not been able to identify why this is happening?
I 've tried fiddling on the live website with a very slight variation of your code and it seems to work:
$('.vma_overlay').on('click', function() {
var $videoSrcOriginal = $(this).siblings('.vma_iFramePopup').attr("src");
if ($videoSrcOriginal.indexOf('?') > -1) {
$('#vma_ModalBox').show();
var $videoSrcAuto = $videoSrcOriginal + "&autoplay=1&mute=1";
$('#vma_ModalBox #vma_video').attr('src', $videoSrcAuto);
$('body').addClass("modalyt");
}
});
It turns out the solution in this particular case was to replace:
$(document).ready(function () {
with:
window.onload = function () {
For some reason specific to our setup, the jquery way of getting document ready was not firing.

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

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

Refresh the page after sound is done playing in Javascript/jQuery

Stumped, I want to have a paper crumple sound play when I click the button to clear to localstorage data, but have to refresh the page after the localstorage data is cleared to update the changes, and the refresh is not allowing the sound effect to play. So I want it to wait till the sound effect finishes and then trigger the refresh. Thanks!
My HTML:
<audio controls="controls">
<source src="paper_crumple.mp3" type="audio/mpeg" />
</audio>
<section class="note">
<h3 id="clear">Clear Note</h3>
<h1 id="title" contenteditable="true">Note Title</h1>
<h2 id="date" contenteditable="true">Date Written</h2>
<p id="note" contenteditable="true">Hello! Click on the note card and start editing!
<br>
<br>
Try refreshing the page, notice that your content stays.
<br>
Try closing your browser, shutting your computer off, and then opening it up again.
<br>It still stays! This is all thanks to the html5 localstorage api.
<br>
<br>
Note that the data will not sync between different browsers, computers, or any other devices such as your mobile phone.
<br>
<br>
This note is responsive! Try adjusting your window size and see how the width adjusts.
<br>
Also note that when you get to mobile width, the note adjusts to best take use of the limited space.
<br>
<br>
Tips: You can press ctrl+b for <b>bold</b> text. Similarly you can do the same thing but for <u>underlined</u> or <i>italic text</i>.</p>
</section>
And my JavaScript:
<script class="jsbin" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var title = document.getElementById('title');
$(title).blur(function() {
localStorage.setItem('title', this.innerHTML);
});
// when the page loads
if ( localStorage.getItem('title') ) {
title.innerHTML = localStorage.getItem('title');
}
// to reset
// localStorage.clear();
});
$(function() {
var date = document.getElementById('date');
$(date).blur(function() {
localStorage.setItem('date', this.innerHTML);
});
// when the page loads
if ( localStorage.getItem('date') ) {
date.innerHTML = localStorage.getItem('date');
}
// to reset
// localStorage.clear();
});
$(function() {
var note = document.getElementById('note');
$(note).blur(function() {
localStorage.setItem('note', this.innerHTML);
});
// when the page loads
if ( localStorage.getItem('note') ) {
note.innerHTML = localStorage.getItem('note');
}
// to reset
// localStorage.clear();
});
window.onload = function() {
var clear = document.getElementById("clear");
var myaudio = new Audio('paper_crumple.mp3');
clear.onclick = function() {
myaudio.play()
localStorage.clear()
// window.location.reload()
}
}
</script>
Try using ended event http://dev.w3.org/html5/spec/single-page.html#event-media-ended
clear.onclick = function() {
myaudio.play()
localStorage.clear()
myaudio.onended = function () {
window.location.reload()
}
}
This is basically saying - "After finished playing sound - reload page"
For anyone wanting an answer to this problem, I finally got it to work so I figured I'd share my solution with the community.
Just gave the link an ID and made the content of the href equal to: javascript:void(0);
Clear Note
Then I just put this into file script.js file:
window.onload = function() {
var clear = document.getElementById("clear");
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'paper_crumple.mp3');
audioElement.setAttribute('preload', 'auto');
audioElement.setAttribute('onended', 'window.location.reload()');
function playAudio() {
audioElement.load;
audioElement.play();
};
clear.onclick = function() {
localStorage.clear();
playAudio();
$("#wrapper").addClass("fadeOutDown");
};
};
Hope this helps anyone!

Stop all playing iframe videos on click a link javascript

I have a list of iframe videos in my webpage.
<iframe width="520" height="360" src="http://www.youtube.com/embed/2muxrT5_a6E" frameborder="0" allowfullscreen></iframe>
<iframe width="520" height="360" src="http://www.youtube.com/embed/2muxrT5_a6E" frameborder="0" allowfullscreen></iframe>
<iframe width="520" height="360" src="http://www.youtube.com/embed/2muxrT5_a6E" frameborder="0" allowfullscreen></iframe>
Stop all videos
I need to stop all playing iframe videos on click the link Stop all videos. How can i do that?
Try this way,
<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
<script language="javascript" type="text/javascript">
$(function(){
$('.close').click(function(){
$('iframe').attr('src', $('iframe').attr('src'));
});
});
</script>
Reloading all iframes just to stop them is a terrible idea. You should get advantage of what comes with HTML5.
Without using YouTube's iframe_API library; you can simply use:
var stopAllYouTubeVideos = () => {
var iframes = document.querySelectorAll('iframe');
Array.prototype.forEach.call(iframes, iframe => {
iframe.contentWindow.postMessage(JSON.stringify({ event: 'command',
func: 'stopVideo' }), '*');
});
}
stopAllYouTubeVideos();
which will stop all YouTubes iframe videos.
You can use these message keywords to start/stop/pause youtube embdded videos:
stopVideo
playVideo
pauseVideo
Check out the link below for the live demo:
https://codepen.io/mcakir/pen/JpQpwm
PS-
YouTube URL must have ?enablejsapi=1 query parameter to make this solution work.
This should stop all videos playing in all iframes on the page:
$("iframe").each(function() {
var src= $(this).attr('src');
$(this).attr('src',src);
});
Stopping means pausing and setting the video to time 0:
$('iframe').contents().find('video').each(function ()
{
this.currentTime = 0;
this.pause();
});
This jquery code will do exactly that.
No need to replace the src attribute and reload the video again.
Little function that I am using in my project:
function pauseAllVideos()
{
$('iframe').contents().find('video').each(function ()
{
this.pause();
});
$('video').each(function ()
{
this.pause();
});
}
Here's a vanilla Javascript solution in 2019
const videos = document.querySelectorAll('iframe')
const close = document.querySelector('.close')
close.addEventListener('click', () => {
videos.forEach(i => {
const source = i.src
i.src = ''
i.src = source
})
})
I edited the above code a little and the following worked for me.......
<script>
function stop(){<br/>
var iframe = document.getElementById('myvid');<br/>
var iframe1 = document.getElementById('myvid1');<br/>
var iframe2 = document.getElementById('myvid2');<br/>
iframe.src = iframe.src;<br/>
iframe1.src=iframe1.src;<br/>
iframe2.src=iframe2.src;<br/>
}<br/>
</script>
$("#close").click(function(){
$("#videoContainer")[0].pause();
});
In jQuery you can stop iframe or html video, by using below code.
This will work for single or multiple video on the same page.
var videos = document.querySelectorAll('iframe');
$(".video-modal .fa-times").on("click", function () {
videos.forEach(i => {
let source = i.src;
i.src = '';
i.src = source;
});
$(".video-modal").css("display", "none");
return false;
});
})
Reload all iframes again to stop videos
Stop all videos
function stop(){
var iframe = document.getElementById('youriframe');
iframe.src = iframe.src;
}
You can modify this code with an iteration
/**
* Stop an iframe or HTML5 <video> from playing
* #param {Element} element The element that contains the video
*/
var stopVideo = function ( element ) {
var iframe = element.querySelector( 'iframe');
var video = element.querySelector( 'video' );
if ( iframe ) {
var iframeSrc = iframe.src;
iframe.src = iframeSrc;
}
if ( video ) {
video.pause();
}
};
OWNER: https://gist.github.com/cferdinandi/9044694
also posted here (by me): how to destroy bootstrap modal window completely?

Categories