Enabling just one audio stream on a webpage - javascript

I'm in the early stages of setting up a band site where there are a number of sample audio streams. Each stream is triggered or stopped by separate "Play" and "Pause" buttons. There are also a number of videos on the page which have their own controls. I used the following code for setting up the audio samples:
$("#play0").click(function() {
$("#audio0").trigger('play');
});
$("#pause0").click(function() {
$("#audio0").trigger('pause');
});
The "audio0" ID is for each audio stream (up to "audio9") while "play0" and "pause0" IDs (also up to "play/pause9") are for buttons. How can I make sure that at any one time, only one audio file should be playing (irrespective of whether it is audio or video). In other words, a user cannot trigger more than one audio stream to play simultaneously. Thank you.

Try something like this
var media = $('audio, video');
function pauseAll() {
media.each(function() {
var element = $(this).get(0);
element.pause();
});
}
$("#play0").click(function(){
pauseAll();
$("#audio0")[0].play();
});

Related

Differentiate between audio start and audio play(after a pause) in HTML5 <audio>

How to add a listener on audio/video start?
I can do it like:
$audio.on("play", function() {
console.log("audio played");
});
where $audio is a jQuery object representing the single DOM audio element.
but it will also run when we resume the video. I want it to run on start only.
One way I can do it is:
$audio.on("play", function() {
if(this.currentTime === 0) {
console.log("audio started);
}
});
but this will run multiple times when we play/pause the audio on the start.
Is there any better way to do this? The listener should only work on audio start and audio replayed, not when the user manually drags the seek bar to the beginning of the source.
Store a flag into the data-* attribute of the targeted element:
const $audio = $('.audio');
$audio.on("play", function() {
if ($(this).data('once-played')) return; // Do nothing if data exists.
// Your code here
console.log("Audio started for the first time");
// Finally, add a flag.
$(this).data('once-played', true);
});
<audio class="audio" src="http://upload.wikimedia.org/wikipedia/en/4/45/ACDC_-_Back_In_Black-sample.ogg" autoplay controls loop></audio>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Actually, it might be sounding confusing because I was under the impression that there could be a possibility that currentTime could still return 0 if we do it in a fraction of seconds. But after reading #freedomn-m, #roko-c-buljan, #rory-mccrossan comments, I got it that it will never be possible that currentTime returns 0 when we play-pause-play the video immediately.
Now, let's say I want to track how many times a user has watched the video. The requirements might sound weird but by watched I only meant started/replayed. It doesn't count if the user manually drags the seek bar to the beginning of the source.
Here is how I implemented it finally using all your points:
const $audio = $('.audio');
$audio.on("play", function() {
if ($(this).data('once-played')) return; // Do nothing if data exists.
// Your code here
console.log("Audio started/replayed");
// Finally, add a flag.
$(this).data('once-played', true);
});
$audio.on("ended", function() {
$(this).data('once-played', false);
});

Preload Javascript audio to play in script

I have a simple program where I run this script:
function PlayAudio(Location){
var audio = new Audio(Location);
audio.Play()
}
in an onclick HTML attribute. I have a fancy loading picture that I know how to make appear and have successfully made it work. I would like to show this picture while the audio is loading, and then make it go away after the audio file is done loading and ready to play. Right now, there is a considerable delay between clicking the element and hearing the sound.
My trouble is knowing when the audio is done loading and ready to play. I figure the best way to know when it's complete loading is to preload the file in-script. I don't know how to do that.
And that's my question:
How do you preload files inside a script?
Or, is there a way to know when an audio file is finally playing?
Note: I cannot use an <audio> element, unless there is some way to nest a <div> inside the <audio> so that the sound in the <audio> is triggered by clicking anywhere in the content of the <div>
Sorry for my slightly confusing descriptions!
Thanks,
Lucas N
You can use canplaythrough event
Sent when the ready state changes to CAN_PLAY_THROUGH, indicating that
the entire media can be played without interruption, assuming the
download rate remains at least at the current level.
function PlayAudio (Location){
var audio = new Audio;
audio.oncanplaythrough = function(event) {
// do stuff, e.g.; set loading `img` `style` `display` to `none`
this.play();
}
audio.src = Location;
}
You change its preload attr by
. audio.preload = "auto";
It will load the whole audio file on start

Creating a Javascript audio playlist with only play and pause

I want to create an audio playlist that can only play and pause. However, when the user is done listening to the entire song, I want to be able for that user to re-play the song.
Currently, the Javascript playlist only plays and stops the music. My pause button is not really working like a pause button. Not sure where I went wrong. And how exactly can I get the song to automatically re-set to the beginning once the user finishes listening to the song? I would very much appreciate the help on this! I wrote the HTML audio code already and just listed the Java Script below.
<script> // play/pause button
$(function() {
$('#play').click(function(){
$('#pause').attr('src',"media/pause.png");
});
});
$(".playBtn").on('click', function() {
var target = $(this).attr("target");
$("#audio").attr("src",target);
$("#audio").trigger("play");
});
$(".pauseBtn").on('click', function() {
$("#audio").trigger("pause");
});
});
</script>
Audio tags have several events to which you can add listeners. Here is a link to a list of them: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events
The "ended" event triggers when the audio is finished playing, so it could help with resetting the song to the beginning when the audio reaches the end.
$("#audio").on("ended", function () {
this.currentTime = 0;
});
You can use loop attribute at <audio> element to continuously loop single audio source. Substitute caching <audio> DOM element for jQuery object to call .play(), .pause() at click events.
javascript
$(function() {
var audio = $("#audio")[0];
$(".playBtn").on("click", function() {
audio.play()
});
$(".pauseBtn").on("click", function() {
audio.pause()
});
})
html
<audio id="audio" src="/path/to/audio/source" loop autoplay controls></audio>
<button class="playBtn">Play</button>
<button class="pauseBtn">Pause</button>
jsfiddle https://jsfiddle.net/kkf33dpr/

Javascript Add Event Listener for change in Audio Volume

I am trying to save the volume of a playing music file in a cookie so when the page is reloaded, the volume the user chose last is maintained, rather than turning up super loud or whatever.
Here's my test code for the eventlistener:
var myAudio = document.getElementById("audio1");
myAudio.addEventListener('change',alert("Audio Volume Changed"),true};
However, it does not respond when I change the volume. I've searched and despite it being something I think is pretty practical, there's no information on it.
You're looking for the "volumechange" event.
var audio = document.getElementById('sample');
audio.addEventListener('volumechange', function() {
console.log('changed.', arguments);
}, false);
I'm using the bubble phase(as opposed to capture) in this example.
http://jsfiddle.net/426E6/
http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#event-definitions

Pause all other players besides activated one. jQuery audio plugin for <audio> element

I've got this plugin which applies different style to html5 <audio> element and provides flash fallback to browsers that don't support .mp3 file format. Problem I encountered is that once you start playing one song, and then click play on any other song, all of them will play at the same time, which is bad user experience.
I was trying to figure out how to edit plugin to make it only play one song at a time, so say if user listens to one song and then click play on other, first one should pause, and so on.
I'm not entirely sure, but I think something need's to be edited along these lines:
playPause: function() {
if (this.playing) this.pause();
else this.play();
},
However, there are various places in the plugin which seem to deal with playing and pausing song, so I'm not sure that this is exact correct line for this. I'm still very new to jQuery, and can't entirely figure out how this big audio library works, I've been reading through code comment's , but still am unable to figure this out.
Full code of the plugin is available here: http://freshbeer.lv/mg/js/audio.min.js Official plugin website: http://kolber.github.io/audiojs/
You can visit my demo page to see the issue, just click play on several players and you will see that they all play at the same time: http://freshbeer.lv/mg/index.html
Use the addEventListener and the play event. This pauses all players except the one that the play button has been pressed on.
audiojs.events.ready(function () {
var as = audiojs.createAll();
$('audio').each(function () {
var myAudio = this;
this.addEventListener('play', function () {
$('audio').each(function () {
if (!(this === myAudio)) {
this.pause();
}
});
});
});
});

Categories

Resources