Minimalistic play() and pause() audio solution - javascript

I found a little code snippet within another question, playing an mp3 just with jquery play() and pause():
<a href="#" rel="http://www.uscis.gov/files/nativedocuments/Track%2093.mp3"
class="play">Play</a>
<div class="pause">Stop</div>
<script>
$(document).ready(function() {
var audioElement = document.createElement('audio');
var source = $('.play').attr('rel');
audioElement.setAttribute('src', source);
//audioElement.setAttribute('autoplay', 'autoplay');
audioElement.load()
$.get();
audioElement.addEventListener("load", function() {
audioElement.play();
}, true);
$('.play').click(function() {
audioElement.play();
});
$('.pause').click(function() {
audioElement.pause();
});
});
I get the audio source from the rel attribute of the "play"-link. Now I would like to add more audio links and make the source relative to their rel attributes.
I tried
var source = $(this).attr('rel');
and also .find() and .each(), but nothing worked so far. I've set up a jsfiddle with two audio links, where only the first audio file will be played. (The fiddle links to an external script, which the client uses on his site, where only jquery 1.4.3 is loaded, but I guess it's possible anyway. I just don't want to use an audio player plugin, I aim for a minimalistic solution.)
Any help would be highly appreciated!

You can update your script to create one audio tag per container:
$(document).ready(function () {
// For each container div
$(".container").each(function() {
// Create the HTML5 <audio> tag
var audioElement = document.createElement('audio');
// Find the play/pause buttons
var $play = $(this).find(".play");
var $pause = $(this).find(".pause");
// Load the source from the play button
var source = $play.attr('rel');
audioElement.setAttribute('src', source);
$.get();
// Play the sound when loaded
audioElement.addEventListener("load", function () {
audioElement.play();
}, true);
// When the user clicks on the play button, play the audio
$play.click(function () {
audioElement.play();
});
// When the user clicks on the pause button, pause it
$pause.click(function () {
audioElement.pause();
});
});
});
And updated Fiddle: http://jsfiddle.net/sY7UT/

Related

How can I make an audio sound play only once using JQuery?

So I have a div that plays an mp3 sound when it is clicked. Instead of playin once. It continues to play over and over again. The snippet of code is:
$(".g-contain").click(function() {
audioElement.play();
});
This may be irrelevant but I figure I should show you the overall code:
/* set no cache */
$.ajaxSetup({ cache: false });
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'https://www.dropbox.com/s/k8xaglyd48vbnq1/pacman_chomp.mp3?dl=1');
audioElement.addEventListener('ended', function() {
this.play();
}, false);
$.getJSON("scripts/data", function(data) {
var html = [];
/* loop through array */
$.each(data, function(index, g) {
$(".container").append(
"<div class='g-details'><div class='name'>" +
g.name + "</div>);
// And finally my click call is here
$(".g-contain").click(function() {
audioElement.play();
});
Not sure why the mp3 file keeps playing when g-contain div is clicked
It's due to this code:
audioElement.addEventListener('ended', function() {
this.play();
}, false);
You attached an event listener to the audio element to re-play when the playing is ended. So once it's played (with click) it will play infinitely.
From the MDN ended event Reference:
ended
The ended event is fired when playback or streaming has stopped
because the end of the media was reached or because no further data is
available.
Just get rid of this code.

Toggle audio "start/stop" with click of image

Could someone please help me add some simple functionality to this string?
Here is what I use to allow people to click on an image and play an audio file...the song plays until its over and wont stop. I would like to allow people to click it a second time to stop the song, and reset it back to the beginning:
$(document).ready(function()
{
var element = $('#starspangledbanner');
var audio = new
Audio('http://siteassets.starspangledbanner.mp3');
element.click(function(e)
{
e.preventDefault();
audio.play();
});
});
Thanks in advance.
You can follow this code. It's very easy and woks fine:
$(document).ready(function(){
var element = $('#starspangledbanner'),
audio = new Audio('http://siteassets.starspangledbanner.mp3');
element.click(function(e){
e.preventDefault();
if(audio.paused){
audio.play();
}else{
audio.pause();
audio.currentTime = 0;
}
});
});

Playing Audio Using Jquery

I have a small jQuery function to play audio when a user clicks the link. I don't need any controls, they are short samples. I just want to play anytime a user clicks. Here is the html for the section that should play;
</div class="classicalRecordings">
Open song
</div>
Then this is the jQuery to play the sound;
function playMusic(){
var audioElement = document.createElement('audio');
var audioElementSrc = $(this).attr('data-audio-src');
audioElement.setAttribute('src', audioElementSrc);
$.get();
audioElement.addEventListener("load", function(){
audioElement.play();
}, true);
}
$(function(){
$('.play').click(playMusic);
});
It doesn't seem to work. I think it has to do with the src variable, I am not sure I am passing it to the audioElement correctly. I have tested using an alert to be sure I am grabbing the data-audio-src correctly. Any help is appreciated.
I think that the event you're looking for is the loadeddata event.
function playMusic(){
var audioElement = document.createElement('audio');
var audioElementSrc = $(this).attr('data-audio-src');
audioElement.setAttribute('src', audioElementSrc);
$.get();
// changed "load" t0 "loadeddata"
audioElement.addEventListener("loadeddata", function(){
audioElement.play();
}, true);
}
$(function(){
$('.play').click(playMusic);
});
Although you could probably be better off having a static audio element and changing the src attribute on user clicks rather than creating a new audio element.
// example
var audio = document.getElementsByTagName('audio')[0];
audio.addEventListener('loadeddata', function() {
this.play();
}, true);
function playMusic() {
var audioElementSrc = $(this).attr('data-audio-src');
audio.setAttribute('src', audioElementSrc);
};
$('.play').click(playMusic);
There is a framework for this that is worth checking out. ListenJS. I wrote it :)
Try something like this:
<audio id="sound">
<source src="music/classical/open.mp3" type="audio/mpeg">
</audio>
And from code:
$(function(){
$('#sound').get(0).play();
});

MediaElement.js: Trigger event, if some specific audio file has ended

Referring to MediaElement.js. How to trigger an event (call a function), if some specific audio file has ended?
var myAudioFiles = ['audioFile1.wav', 'audioFile2.wav', 'audioFile3.wav'];
var myPlayer = new MediaElementPlayer('#myPlayer');
myPlayer.setSrc(myAudioFiles[0]);
myPlayer.play();
Pseudo Code:
if (hasEnded(myAudioFiles[0])) {
doSomething();
}
Please try this.
$(function(){
$('audio,video').mediaelementplayer({
success: function(player, node) {
player.addEventListener('ended', function(e){
player.src = 'media/somefile.mp4';
player.load();
player.play();
});
}
});
});
copied from here:
mediaelement.js - play another video at end of 1st video

HTML5/JavaScript/jQuery audio playlist

I've got this JavaScript/jquery code:
$(document).ready(function() {
var audioElement = document.createElement('audio');
var secondtrack = 'hangover.ogg';
audioElement.setAttribute('src', 'hangover.ogg');
audioElement.load()
audioElement.addEventListener("load", function() {
audioElement.play();
}, true);
$('#play').click(function() {
audioElement.play();
});
$('#pause').click(function() {
audioElement.pause();
});
});
How could I get another song started after the first ended?
The AUDIO element should fire a "ended" event though I am not sure how well this is supported at the moment.
So you could try something like that:
audioElement.addEventListener('ended', function () {
// Play another song
});
See also:
http://dev.w3.org/html5/spec/Overview.html#event-media-ended

Categories