Preload audio and apply css during playback - php

I am looking to create sound buttons.
Have used the answer here:
Buttons click Sounds
and implemented it so that the buttons are divs and created dynamically from a MySQL DB.
Does anyone know how to preload that list of sounds on page load?
Also, I want to apply a CSS class to the div when clicked and then when the audio finishes, want it to switch back to the original CSS class.
This is what I have tried. The sounds play correctly but the onended fuction does not fire.
<script type='text/javascript'>
$(window).load(function(){
var baseUrl = "http://[URL HERE]";
var audio = [<?php echo $audiostring; ?>];
$('div.ci').click(function() {
var i = $(this).attr('id').substring(1);
mySound = new Audio(baseUrl + audio[i-1]).play();
mySound.onended = function() {
alert("The audio has ended");};
});
});
</script>

If you are using HTML5 audio you can do something like the following:
mySound.addEventListener("ended", function()
{
alert("The audio has ended");
});
Edit:
Try changing the way you create the audio tag, as referenced here.
$('div.ci').click(function() {
var i = $(this).attr('id').substring(1);
mySound = $(document.createElement('audio'));
mySound.src = baseUrl + audio[i-1];
mySound.play();
mySound.addEventListener("ended", function()
{
alert("The audio has ended");
});
});

<audio> and new Audio() should be the same but it doesn't look
like that is the case in practice. Whenever I need to create an audio
object in JavaScript I actually just create an element like
this:
The ended event is created based on .currentTime attribute. event-media-ended
the canplaythrough event was used to knowing when the browser has finished downloading the audio file and we can play
code complete use closest
<style type="text/css">
body{background: #aaa;color:#fff;}
div
{
width: 100px;
height: 100px;
background: #dda;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div >
</div>
<div >
</div>
<div >
</div>
<script type="text/javascript">
$(window).load(function(){
var audioFiles = [
"http://www.soundjay.com/button/beep-01a.mp3",
"http://www.soundjay.com/button/beep-02.mp3",
"http://www.soundjay.com/button/beep-03.mp3",
"http://www.soundjay.com/button/beep-05.mp3"
];
function Preload(url) {
var audio = new Audio();
// once this file loads, it will call loadedAudio()
// the file will be kept by the browser as cache
audio.addEventListener('canplaythrough', loadedAudio, false);
audio.src = url;
}
var loaded = 0;
function loadedAudio() {
// this will be called every time an audio file is loaded
// we keep track of the loaded files vs the requested files
loaded++;
if (loaded == audioFiles.length){
// all have loaded
init();
}
}
var player = document.createElement('audio');
function playAudio(index) {
player.src = audioFiles[index];
player.play();
}
function init() {
$('div').click(function(event) {
$(this).css('background', 'blue');
playAudio(Math.floor(Math.random()*audioFiles.length));
player.addEventListener("ended", function(){
player.currentTime = 0;
$(event.target).closest('div').css('background', '#dda');
});
});
}
// We begin to upload files array
for (var i in audioFiles) {
Preload(audioFiles[i]);
}
});
</script>

Related

How to transfer the image data uploaded using jquery to php?

I have a code here
<h2>Click blue button</h2>
<button id="open_btn" class="btn btn-primary">Open dialog</button>
<div id="output"></div>
<script src="src/bootstrap.fd.js"></script>
<script type="text/javascript">
$("#open_btn").click(function() {
$.FileDialog({multiple: true}).on('files.bs.filedialog', function(ev) {
var files = ev.files;
var text = "";
files.forEach(function(f) {
text += f.name + "<br/>";
});
$("#output").html(text);
}).on('cancel.bs.filedialog', function(ev) {
$("#output").html("Cancelled!");
});
});
</script>
its a drag and drop upload using jquery and boostrap layout from http://www.jqueryscript.net/demo/Drag-Drop-File-Upload-Dialog-with-jQuery-Bootstrap. Its working, but the problem is, I don't know how to pass the data uploaded to php for processing and put the file into the server.
Anyone can help me with this?
you can try using ajax. Setup ajax in your project from tons of tutorials available on the net.
After that in your javascript function i suppose you want to pass variable text to php. So here's what you can do when you get a little hang about ajax by going through the tutorials
<script type="text/javascript">
$("#open_btn").click(function() {
$.FileDialog({multiple: true}).on('files.bs.filedialog', function(ev) {
var files = ev.files;
var text = "";
files.forEach(function(f) {
text += f.name + "<br/>";
});
$.ajax({
url: "'your php function name'?name ="+text,
success: function( data ) {
if(data == "retn value") { //return value of the php function
// alert("");
} else {
}
}
});
$("#output").html(text);
}).on('cancel.bs.filedialog', function(ev) {
$("#output").html("Cancelled!");
});
});
</script>
create a function in php which will take your data as an argument.
hope this helps.

Play a certain audio track when clicked

All the songs have a .song class but it plays the first song on the playlist. It's basically the play button for the whole playlist. I've play around with this for awhile and I can't seem to get it right. It might be the simplest thing too. I have the song populate with php depending on the album. I want people to be able to click a certain song and that song plays.
example: http://mixtapemonkey.com/mixtape?m=637
Also if you know how to toggle between the play and stop button, that would be nice to throw in there too. Thanks!
<script>
jQuery(document).ready(function(){
i=0;
nowPlaying = document.getElementsByClassName('playsong');
nowPlaying[i].load();
$('.play').on('click', function() {
nowPlaying[i].play();
callMeta();
});
$('.song').on('click', function() {
nowPlaying[i].play();
callMeta();
});
$('.pause').on('click', function() {
nowPlaying[i].pause();
callMeta();
});
$('.next').on('click', function() {
$.each($('audio.playsong'), function(){
this.pause();
});
++i;
nowPlaying[i].load();
nowPlaying[i].play();
callMeta();
})
function callMeta(){
var trackTitle = $(nowPlaying[i]).attr('data-songtitle');
$('.songtitle').html(trackTitle);
var trackArtist = $(nowPlaying[i]).attr('data-songartist');
$('.songartist').html(trackArtist);
}
})
You have to target the audio element inside each .song, now you're always targeting the first one.
To toggle, check if the audio is paused, and play() or pause() accordingly :
$('.song').on('click', function() {
var audio = $('.playsong', this).get(0);
if (audio.paused) {
audio.play();
}else{
audio.pause()
}
callMeta();
});
EDIT:
with a few changes, I'm guessing something like this would work :
jQuery(document).ready(function($){
var audios = $('.playsong');
var audio = audios.get(0);
audio.load();
$('.play').on('click', function() {
callMeta(audio);
});
$('.song').on('click', function() {
audio = $('.playsong', this).get(0);
callMeta(audio);
});
$('.pause').on('click', function() {
audio.pause();
});
$('.next').on('click', function() {
var i = audios.index(audio);
audio = $(audios).get(i+1);
callMeta(audio);
});
function callMeta(elem){
audios.each(function(i,el) {
if (!el.paused) {
el.pause();
el.currentTime = 0;
}
});
elem.load();
elem.play();
$(elem).on('ended', function() {
$('.next').trigger('click');
});
$('.songtitle').html($(elem).attr('data-songtitle'));
$('.songartist').html( $(elem).attr('data-songartist') );
}
});
Just for clarity - you say the songs have class "song", yet your code says "playsong". A typo, perhaps?
The first song always plays because you always play nowPlaying[i], and i=0 - which only changes when $('.next').on('click', function(){}) is called! You need a way to either change i when a song is clicked, or make the HTML more "modular" (I use this loosely) around each song.
Example HTML:
<audio id="coolSong1">
<!-- Sources -->
</audio>
<!-- I'm not sure what you're using as play, pause, next buttons, so I'll use buttons -->
<input type="button" class="play" name="coolSong1" value="play" />
<input type="button" class="pause" name="coolSong1" value="pause" />
<input type="button" class="next" name="coolSong1" value="next" />
Corresponding script:
$(".play").click(function(event) {
document.getElementById(event.target.name).play();
});
$(".pause").click(function(event) {
document.getElementById(event.target.name).pause();
});

div refresh javascript

I am using a div refresh script (Given below). The contents of the div contains an auto scroll ul (code from http://www.dynamicdrive.com/). The refresh is working properly. But after the refresh the auto scrolling is not working
Code for refresh
<script type="text/javascript">
window.onload = setupRefresh;
function setupRefresh()
{
setInterval("refreshBlock();",1000);
}
function refreshBlock()
{
$('#list4').load("refreshpage");
}
</script>
Code for auto scroll
<script type="text/javascript">
var delayb4scroll=2000 //Specify initial delay before marquee starts to scroll on page (2000=2 seconds)
var marqueespeed=1 //Specify marquee scroll speed (larger is faster 1-10)
var pauseit=1 //Pause marquee onMousever (0=no. 1=yes)?
var copyspeed=marqueespeed
var pausespeed=(pauseit==0)? copyspeed: 0
var actualheight=''
function scrollmarquee(){
if (parseInt(cross_marquee.style.top)>(actualheight*(-1)+8))
cross_marquee.style.top=parseInt(cross_marquee.style.top)-copyspeed+"px"
else
cross_marquee.style.top=parseInt(marqueeheight)+8+"px"
}
function initializemarquee(){
cross_marquee=document.getElementById("vmarquee")
cross_marquee.style.top=0
marqueeheight=document.getElementById("list4").offsetHeight
actualheight=cross_marquee.offsetHeight
if (window.opera || navigator.userAgent.indexOf("Netscape/7")!=-1){ //if Opera or Netscape 7x, add scrollbars to scroll and exit
cross_marquee.style.height=marqueeheight+"px"
cross_marquee.style.overflow="scroll"
return
}
setTimeout('lefttime=setInterval("scrollmarquee()",30)', delayb4scroll)
}
if (window.addEventListener)
window.addEventListener("load", initializemarquee, false)
else if (window.attachEvent)
window.attachEvent("onload", initializemarquee)
else if (document.getElementById)
window.onload=initializemarquee
</script>
Could some one please help?
It seems like you need to call initializemarquee() after the load is complete. You can do this in the .load()'s callback.
function refreshBlock(){
$('#list4').load("refreshpage", function(){
clearInterval(lefttime);
initializemarquee()
});
}
I almost forgot to add that you'd also want to stop that interval.
You just need:
function refreshBlock()
{
$('#list4').load("refreshpage");
initializemarquee();
}
Why the mix of plain JS and jQuery? If you have jQuery use it
Here is my rewrite. Not tested but apart from typos or things that I thought could be done in jQuery and cannot, it should do the whole thing
$(function() {
var sId = setInterval(function {
$('#list4').load("refreshpage");
},1000);
var $cross_marquee=$("#vmarquee")
var delayb4scroll=2000 //Specify initial delay before marquee starts to scroll on page (2000=2 seconds)
var marqueespeed=1 //Specify marquee scroll speed (larger is faster 1-10)
var pauseit=true //Pause marquee onMousever (false=no. true=yes)?
var copyspeed=marqueespeed;
var pausespeed=(pauseit==0)? copyspeed: 0;
var actualheight=$cross_marquee.height();
var marqueeheight=$("#list4").height();
$cross_marquee.top(0);
if (window.opera || navigator.userAgent.indexOf("Netscape/7")!=-1){ //if Opera or Netscape 7x, add scrollbars to scroll and exit
$cross_marquee.height(marqueeheight);
$cross_marquee.css("overflow","scroll");
}
else var tId = setTimeout(function() {
lefttime=setInterval(
function() {
var top = $cross_marquee.top();
if (top>(actualheight*(-1)+8)) $cross_marquee.top(top-copyspeed)
else $cross_marquee.top(marqueeheight+8);
}
},30)
, delayb4scroll);
});

How to make a secondary document ready function?

Ok this is my issue if anyone can help, please.
I have a href that div id to switch content - I would like to add another document ready function javascript without conflicting with make tab I have already.
Example of make tab already:
<script type="text/javascript">
{literal}
$(document).ready(function(){
function makeTabs(selector) {
var tabContainers = $(selector + ' > div');
tabContainers.removeClass("selected").filter(':first').addClass("selected");
galleryRendered = false;
$(selector + ' > ul a').click(function () {
tabContainers.removeClass("selected");
tabContainers.filter(this.hash).addClass("selected");
$(selector + ' > ul a').removeClass('selected');
$(this).addClass('selected');
if (this.hash == '#Pictures' && !galleryRendered)
{
var galleries = $('.pictures > .ad-gallery').adGallery({
effect : 'slide-hori',
enable_keyboard_move : true,
cycle : true,
animation_speed : 400,
slideshow: {
enable: false
},
callbacks: {
init: function() {
this.preloadImage(0);
this.preloadImage(1);
this.preloadImage(2);
}
}
});
galleryRendered = true;
}
if (this.hash == '#OnTheMap') document.getElementById("Map").map.onContainerChanged();
return false;
}).filter(':first').click();
}
makeTabs('.tabs');
});
{/literal}
</script>
Want to create a second one so I can create tabs inside of an existing div id area/content to switch from photo to video to youtube.
<div class=".tabs"><ul><li>[[Photo]]</li><li>[[Youtube]]</li><li>[[Video]]</li></ul><div id="photo">Test</div><div id="tube">Test</div><div id="vid">Test</div></div>
This will be inside a div id that already exist that uses the first tab creator shown above.
In jQuery you just have to do this:
$(function(){
// code here
});
$(function(){
// more code here
});
Every function declared like this will be executed on domready.

Overriding window = onload

I have a page within wordpress that I want to password protect via a user role plugin. Everything works fine on straight forward pages but I have a page with window.onload = function() { that completely overrides the password function.
I want the page to load immediately after it's checked to see if the user is logged in or not.
Update:
I'm using this plugin and I just have the function:
<script type="text/javascript">
(function() {
window.onload = function() {
var map = new google.maps.Map(document.getElementById('map'), options);
...
} } )
</script>
Which then loads on this div:
<div id="map" style="width:100%; height:100%"></div>
You have to use addEventListener or attachEvent to load multiple functions. If you want to use window.onload = .., use the code in the last else block at the function below:
function addEvent(name, func) {
if (window.addEventListener) {
window.addEventListener(name, func, true);
} else if(window.attachEvent) {
window.attachEvent('on' + name, func);
} else {
var other_func = typeof window['on'+name] == "function" ? window['on'+name] : function(){};
window['on' + name] = function(ev){
func(ev);
other_func(ev);
}
}
}
addEvent('load', function(){
//Load function
});
Instead of assigning it directly to the onload property add it as an event listener
https://developer.mozilla.org/en/DOM/element.addEventListener
You'll need to use attachEvent for IE versions < 9.
http://msdn.microsoft.com/en-us/library/ms536343(v=vs.85).aspx
If you're using a framework such as jQuery or Prototype this can be abstracted out so you don't need to worry about different browsers.

Categories