I am trying to implement a very minimal audio player for a web site.
The interface is rather simple. It has a play/pause button, and a mute/unmute button.
The problem I have is implementing multiple instances of the same player for different tracks.
The javascript for the player is:
jQuery(function() {
var myAudio = document.getElementById("myAudio");
var btnPlayPause = document.getElementById("btnPlayPause");
var btnMute = document.getElementById("btnMute");
btnPlayPause.addEventListener("click", function() {
if (myAudio.paused || myAudio.ended) {
myAudio.play();
btnPlayPause.innerHTML = "<span aria-hidden=\"true\" data-icon=\"\"></span><span class=\"screen-reader-text\">Play</span>";
}
else {
myAudio.pause();
btnPlayPause.innerHTML = "<span aria-hidden=\"true\" data-icon=\"\"></span><span class=\"screen-reader-text\">Pause</span>";
}
});
btnMute.addEventListener("click", function() {
if (myAudio.muted) {
myAudio.muted = false;
btnMute.innerHTML = "<span aria-hidden=\"true\" data-icon=\"\"></span><span class=\"screen-reader-text\">Mute</span>";
}
else {
myAudio.muted = true;
btnMute.innerHTML = "<span aria-hidden=\"true\" data-icon=\"\"></span><span class=\"screen-reader-text\">Unmute</span>";
}
});
});
This works fine for a single track. But if I have multiple tracks on the same page, this becomes a problem.
I am guessing that I need some modification to the syntax where I define the myAudio variable:
var myAudio = document.getElementById("myAudio");
However, I am not sure how to change that so the same script can control multiple audio tracks.
If possible, I also would like to be able to ensure that if the user clicks the play button on a different track, the track that is currently playing "stops" or is "paused" and the new track starts (so 2 tracks are not playing on top of each other).
This is jQuery based solution. To make HTML5 audio work also in IE8/7 use some additional flash fallback.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.10.1.js'></script>
<style type='text/css'>
.mp3Player {
padding:8px;
margin:8px;
background-color:#ddf;
}
</style>
<script type='text/javascript'>//<![CDATA[
jQuery(function (){
var myAudio = document.getElementById("myAudio");
var current = null;
var playingString = "<span aria-hidden=\"true\" data-icon=\"\"></span><span class=\"screen-reader-text\">Pause</span>";
var pausedString = "<span aria-hidden=\"true\" data-icon=\"\"></span><span class=\"screen-reader-text\">Play</span>";
$(document.body).on('click', '.btnPlayPause',function(e){
var target = this;
//console.log(target, current); //return;
if (current == target) {
target.innerHTML = pausedString;
target.parentNode.setAttribute('data-pos', myAudio.currentTime); //start from paused
myAudio.pause();
current = null;
} else { // current!=target
if (current != null) {
current.innerHTML = pausedString;
current.parentNode.setAttribute('data-pos', '0'); //reset position
target.parentNode.setAttribute('data-pos', myAudio.currentTime); //start from paused
}
current = target;
target.innerHTML = playingString;
if(myAudio.canPlayType && myAudio.canPlayType("audio/mpeg") != "") { // MP3
myAudio.src = target.parentNode.getAttribute('data-src');
} else if(myAudio.canPlayType && myAudio.canPlayType("audio/ogg") != "") { // OGG
myAudio.src = target.parentNode.getAttribute('data-src2');
} else {
return; // no audio support
}
myAudio.play();
myAudio.onloadeddata = function () {
myAudio.currentTime = parseFloat(target.parentNode.getAttribute('data-pos'));
};
}
});
$(document.body).on('click', '.btnMute',function(e){
myAudio.muted = !myAudio.muted;
$('.btnMute').each(function(){
if (myAudio.muted) {
this.innerHTML = "<span aria-hidden=\"true\" data-icon=\"\"></span><span class=\"screen-reader-text\">Muted</span>";
} else {
this.innerHTML = "<span aria-hidden=\"true\" data-icon=\"\"></span><span class=\"screen-reader-text\">Audible</span>";
}
});
});
});
//]]>
</script>
</head>
<body>
<audio id="myAudio"></audio>
<div class="mp3Player" data-src="a.mp3" data-src2="a.ogg" data-pos="0">
<button class="btnPlayPause button">►||</button>
<button class="btnMute button">MUTE</button>
<span class="infoLabel">Audio #1</span>
</div>
<div class="mp3Player" data-src="b.mp3" data-src2="b.ogg" data-pos="0">
<button class="btnPlayPause button">►||</button>
<button class="btnMute button">MUTE</button>
<span class="infoLabel">Audio #2</span>
</div>
</body>
</html>
jQuery code + result page.
javascript code + result page.
Both scripts need additional existing .mp3 files to play the sound
Related
i am currently practicing my html and js skills and i have this code which is when i click the unlock button the audio will automatically play but the problem is even the unlock code is wrong the audio will still play this is my html on the button and on the audio
the audio tag:
<audio id="music" src="bgmusic.mp3" controls hidden loop></audio>
the button tag:
<button id="unlock" class="round pink" onclick="playAudio()">
Unlock
</button>
and here's my current js for the onlick event on the button
var x =
document.getElementById("music");
function playAudio() {
x.play();
}
that is my current syntax but what i want to happen is when the audio will only play if i enter the correct code
and here's the js function for the unlock code functionality:
var number = 0;
$('#unlock').on('click', function(event) {
event.preventDefault();
event.stopPropagation();
$('#textMachine').css('display', 'inline-block');
var code = '';
$.each($('.code'), function(i, v) {
code += $(v).val();
});
if(code == '30')
{
// success
var machine = $('#textMachine').slotMachine({
active: 0,
delay: 500,
randomize : function(activeElementIndex){
return 3;
}
});
machine.setRandomize(3);
machine.shuffle(5, function(){
answerCorrect();
});
} else {
if(number == 3) { number = 0; }
// fail
var machine = $('#textMachine').slotMachine({
active: 1,
delay: 500,
randomize : function(activeElementIndex){
return number;
}
});
machine.shuffle(5, function(){
number++;
});
}
});
var answerCorrect = function() {
$('.login-form').fadeOut();
$('.congratulation-text').fadeIn();
$('.success-area').css('display','block');
};
})();
well actually you can do this
function playSound () {
var audio = new Audio('audio_file.mp3');
audio.play();
}
and you can call it on your button or your function
I've being bashing my head around finding a working solution for this.
Goal is to create a text size switcher for people with poor eyesight.
I have created three span elements with classes small, medium and large.
And I have a piece of code that almost gets the job done but it needs that cookie part.
$(function() {
$(".font-toggle span").click(function() {
var size = $(this).attr('class');
$("body").attr("id", size);
return false;
});
});
How can i use cookies to save my selection and add it after page refresh ?
Have been reading many stackoverflow posts about setting cookies but all of them feature only one toggle. Here I have three.
JSFIDDLE HERE
Many thanks!
$(document).ready(function(){
$(".font-toggle span").click(function() {
var size = $(this).attr('class');
$("body").attr("id", size);
if($.cookie('mycookie') == 'valueOfCookie'){
$.cookie('mycookie', '');
}
else{
$.cookie('mycookie', 'valueOfCookie');
}
return false;
});
if($.cookie('mycookie') == 'valueOfCookie'){
$("body").attr("id", 'big-font');
}
else{
$("body").removeAttr("id");
}
});
#big-font{
font-size: 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://github.com/carhartl/jquery-cookie/releases/download/v1.4.1/jquery.cookie-1.4.1.min.js"></script>
<div class="font-toggle">
<span class="big-font">
Button
</span>
</div>
<div>
Text To Show
</div>
Maybe this will work for you.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://github.com/carhartl/jquery-cookie/releases/download/v1.4.1/jquery.cookie-1.4.1.min.js"></script>
<script>
"use strict";
$(document).ready(function() {
let eyesight = $.cookie('eyesight');
if (eyesight != undefined) {
$("body").addClass(eyesight);
} else
setEyesight('medium'); // Default size
$(".font-toggle span").click(function() {
setEyesight($(this).attr('class'));
});
});
function setEyesight(size) {
let eyesight = $.cookie('eyesight');
if (eyesight != undefined) {
$("body").removeClass(eyesight);
$.removeCookie('eyesight');
}
$("body").addClass(size);
$.cookie('eyesight', size);
}
</script>
What about this?
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://github.com/carhartl/jquery-cookie/releases/download/v1.4.1/jquery.cookie-1.4.1.min.js"></script>
<script>
"use strict";
$(document).ready(function() {
let eyesight = new Eyesight();
eyesight.initialize();
$(".font-toggle span").click(function() {
eyesight.set($(this).attr('class'));
});
});
function Eyesight() {
let self = this;
let name = "eyesight";
let current = null;
let _default = "medium";
let data = $.cookie(name);
// initialzie
this.initialize = function() {
if (data!= undefined) {
$("body").addClass(data);
current = data;
} else
self.set(_default); // Default size
// init cookie listener
self.listener();
};
// set eyesight function
this.set = function(size) {
if (data != undefined) {
$("body").removeClass(data);
$.removeCookie(name);
}
$("body").addClass(size);
$.cookie(name, size);
current = size;
};
// eyesight cookie listener function
this.listener = function() {
setTimeout(function() {
let cookie = $.cookie(name);
if (cookie != undefined && cookie != current)
self.set(cookie);
self.listener();
}, 100);
};
}
</script>
I have the following javascript to make the webpage title change again and again after every five seconds.
<script>
var titleArray = ["TITLE-1","TITLE-2","TITLE-3","TITLE-4"];
var N = titleArray.length;
var i = 0;
setInterval(func,5000);
function func(){
if (i == 4) {
i = 0;
}
document.title = titleArray[i];
i++;
}
</script>
I want it to work only when the user has opened a different tab in order to "attract" him/her back to my site.While he/she is on my site I want this javascript to stop working so the title of the webpage is what I simply write in the title tags.
here is a summary of what I want.
<script>
if (the user is not on this tab but has opened and is using a different tab)
{the javascript I have mentioned above};
elce {nothing so the title tags work};
</script>
P.S: Is this a good idea? Got any other suggestions? I just really like thinking out of the box.
Please try with below script.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var isActive;
window.onfocus = function () {
isActive = true;
};
window.onblur = function () {
isActive = false;
};
// test
var titleArray = ["TITLE-1","TITLE-2","TITLE-3","TITLE-4"];
var N = titleArray.length;
var i = 0;
function changeTitle(){
if (i == 4) {
i = 0;
}
document.title = titleArray[i];
i++;
}
setInterval(function () {
if(window.isActive !== true){
changeTitle();
}
}, 1000);
</script>
I'm working on an online radio website and am trying to detect what state the audio player is currently in for the user.
The current setup I've got is often wrong in knowing this and if I'm on iOS and I pause from the lock screen player instead, it will still think it's playing because I never clicked the html pause button.
Finally how is it possible to detect when my stream has fully ended. I've tried: onstalled="", onwaiting="", onerror="", onended="". But none of them work 100% of the time. The closest one to work would be: onstalled="", but even that only had a 60% success rate or so (occasionally when I'm loading the site it would tell me it has ended).
HTML:
<audio autoplay="" id="player" title="" oncanplay="radioLoaded()">
<source src="...">
</audio>
Javascript:
function radioLoaded() {
if (player.paused) {
document.getElementById('radioplaypause').innerHTML = varRadioResume;
} else if (player.play) {
document.getElementById('radioplaypause').innerHTML = varRadioPause;
} else {
document.getElementById('radioplaypause').innerHTML = varRadioLoading;
}
window.player = document.getElementById('player');
document.getElementById('radioplaypause').onclick = function () {
if (player.paused) {
player.play();
this.innerHTML = varRadioPause;
} else {
player.pause();
this.innerHTML = varRadioResume;
}
}
};
function radioEnded() {
document.getElementById('radiolivetext').innerHTML = 'OFFLINE';
document.getElementById('radioplayer').style.display = 'none';
document.getElementById('radioinformation').style.display = 'none';
};
Try this, with some corrections/notes to the code in general:
function radioLoaded() {
// move this line to the top
window.player = document.getElementById('player'); // !!! <-- name too generic, possibility of global collisions
var playPauseButton = document.getElementById('radioplaypause');
if (player.paused) {
playPauseButton.innerHTML = varRadioResume;
} else if (player.play) {
playPauseButton.innerHTML = varRadioPause;
} else {
playPauseButton.innerHTML = varRadioLoading;
}
playPauseButton.onclick = function () {
if (player.paused) {
player.play();
this.innerHTML = varRadioPause;
} else {
player.pause();
this.innerHTML = varRadioResume;
}
};
player.onended = function () {
console.log('ended');
};
// other helpful events
player.onpause = function () {
console.log('paused...');
}
player.onplay = function () {
console.log('playing...');
}
player.onprogress = function (e) {
console.log(e.loaded + ' of ' + e.total + ' loaded');
}
};
Using the Soundcloud JavaScript SDK I have successfully been able to grab my tracks and play them. My goal is to allow playing and pausing via clicking on one button (like a play/pause toggle). However, my issue is that when I click on the .SCbtn element, the song plays, and doesn't stop. My conditionals seem to be correct because I can see true and false making it into the console. Not quite sure why SC.sound.pause(); isn't working.
var is_playing = false;
var trackCont = function(trackNum){
SC.stream("/tracks/" + trackNum).then(function(sound){
SC.sound = sound;
if (is_playing === false){
SC.sound.play();
is_playing = true;
console.log(is_playing);
}else if(is_playing === true){
SC.sound.pause();
is_playing = false;
console.log(is_playing);
}
});
}
$('body').on("click", ".SCbtn", function(){
var theTrack = $(this).attr('id');
trackCont(theTrack);
});
Update
My Fiddle
I think you're overcomplicating things. Here's a simple example:
HTML:
<script src="https://connect.soundcloud.com/sdk/sdk-3.0.0.js"></script>
<button id="play">Play</button>
JavaScript:
SC.initialize({
client_id: 'XXXX'
});
var myPlayer;
var isPaused = false;
SC.stream('tracks/43377447').then(function(player){
player.play()
myPlayer = player;
});
document.querySelector('button').addEventListener('click', function() {
if (isPaused) {
myPlayer.play()
isPaused = false;
} else {
myPlayer.pause()
isPaused = true;
}
});
Working JSFiddle.
You should use the toggle() method provided by Soundcloud for easiest implementation. See here: https://developers.soundcloud.com/docs/api/html5-widget
Something like the below should do the trick:
var sc = SC.Widget(iframe);
$('body').on("click", ".SCbtn", function(){
sc.toggle();
});