Make a stop button with Javascript - javascript

I thought this would be the easiest part but I guess I'm either having a brain fart or this is more difficult than I thought it'd be, but I can't seem to figure out how to make a stop button for this code. I've tried so many things that just don't seem to work. I want it so that when #stopbutton is pressed it stops audio. I've tried things like
function stopAudio() {
audio.forEach(audio=>audio.pause());
}
$('#stopbutton').click(stopAudio);
function stopAudio() {
audio.pause();
$('#stopbutton').click(stopAudio);
and someothers that didn't work
audio js
function playAudio(e)
{
let el = e.currentTarget;
var audio = new Audio();
var src = "mp3/" + el.id + ".mp3";
audio.src = src;
audio.play();
return audio;
}
html
<span>Sound1X</span>
Between span is all in localStorage btw
This javascript might also be relevant
function createListeners()
{
let names = document.getElementsByName("names2");
for (let i = 0; i < names.length; i++)
{
let name = names[i];
name.removeEventListener('click', playAudio);
name.addEventListener('click', playAudio);
}
}
window.addEventListener('load', function() { createListeners(); });
$(document).on('click', '[name="names2"]', playAudio);

Related

My audio does not play when I click on the play button

This is how my script looks like:
<script>
var obj = document.createElement("audio");
document.body.appendChild(obj);
obj.src = "http://example.com/audios/Kalimba.mp3";
obj.load();
obj.volume = 0.3;
obj.preLoad = true;
obj.controls = true;
$(".testspeech").click(function() {
obj.paused?obj.play():obj.pause()
});
</script>
Then in the HTML I have a button that is meant to play and/or pause the video.
However, when I load the page nothing happens when I click on the play button.
Anything I could have possibly done wrong here?
Here is the HTML:
<button class="testspeech">
play/pause
</button>
As far as I can tell the reason your sound isn't playing is that the src for the actual sound is not valid. I've created a JSFiddle (here) to test it out, and after replacing the sound clip link it works as expected.
$(document).ready(function() {
var obj = document.createElement("audio");
document.body.appendChild(obj);
obj.src = "https://www.kozco.com/tech/piano2.wav";
obj.load();
obj.volume = 0.3;
obj.preLoad = true;
obj.controls = true;
$(".testspeech").on('click', function() {
obj.paused ? obj.play() : obj.pause()
});
});

Does addEventListener work in a while loop?

I am trying to loop through a number of elements to change the audio source of a single audio element, play it, and once ended, change the new src and play it until the loop has gone through all elements:
var contentAudio = new Audio();;
function audioLoop(index, audioModel) {
while (index < audioModel.length) {
var audio = contentAudio;
audio.src = audioModel[index].src;
audio.play()
audio.addEventListener('ended',
function () {
index++;
});
}
console.log('done');
}
It seems that adding the event listener is not working. The audio does not play and I am stuck in an endless loop. The audio ended event is never triggered. Am I doing anything wrong? Is there a better alternative?
The while loop is synchronous so it doesn't wait for your ended event. Here is what I'm suggesting:
var contentAudio = new Audio();
function audioLoop(index, audioModel) {
(function process(done) {
if (index >= audioModel.length) {
done(); return;
}
var audio = contentAudio;
audio.src = audioModel[index].src;
audio.play()
audio.addEventListener('ended', function () {
index++;
process(done);
});
})(function () {
console.log('done');
});
}
Also is audioModel an array. If so I think you should be using audioModel[index].src instead of audioModel.src.

how to make button that plays sample of all audio files in page in javascript?

I have code that dynamically loads audio files from a directory. Right now they play/pause when a div is clicked. Here is my javascript doing that:
function get_list_of_files_from_html( html_string ){
var el = document.createElement( 'html' );
el.innerHTML = html_string;
var list_of_files = el.getElementsByTagName( 'a' );
var return_string ='<UL>';
for(var i=5; i < list_of_files.length ; i++){
var current_string = list_of_files[i];
var new_string =
current_string.toString().replace
(/http:\/\/www.website.com\/~user\/programming\//g,'');
var brand_new = new_string.replace('.mp3','');
return_string += '<div class="floating"
onclick="playAudio(\'audio_tag_id'+i+'\')" >'+brand_new+'<audio
id="audio_tag_id'+i+'"> <source src = "'+current_string+'"
type="audio/mpeg"></audio>';
return_string += '</div>';
}
return return_string;
}
function playAudio(tag_id){
var audio= document.getElementById(tag_id);
return audio.paused ? audio.play() : audio.pause();
}
I want to make a button that plays only like five seconds of each audio file and runs through them in order. Does anyone know how I would go about doing this?
You'll need to work asynchronously, so it's a ping-pong between the main code and a callback. Something like this:
// The click event handler
function onPlayClicked(event){
if (!window.HTMLAudioElement){
console.write("Error: no audio");
return;
}
// toggle the state of the playlist not the actual music player
isPlaying = !isPlaying;
if (isPlaying) startPlaying();
else resetList(); // if clicked while playing
}
// sets timer and plays current
function startPlaying(){
if (isPlaying){ // just checking that no one pressed the STOP in the meantime...
setTimout(done, 5000); // timer callback and miliseconds
playAudio();
}
}
// stops this song and starts next. Callback from timer
function done(){
if (nowPlaying == lastSongIndex(){
pauseAudio();
resetPlaylist();
return;
}
if (isPlaying){
pauseAudio();
nowPlaying++;
startPlaying();
}
// plays current audio
function playAudio(){
// Friendly advice: don't use getElementByTag. There may be other 'a's.
audioList = document.getElementById('audiolist');
audioURL = audioList[nowPlaying]; // nowPlaying advanced by done()
urlregex = '/http:\/\/www.website.com\/~user\/programming\//g';
audioData = audioUrl.remove(urlregex).replace('.mp3','');
player = document.getElementById('audioplayer');
player.src = audioData;
player.play();
}
function pauseAudio(){
player = document.getElementById('audioplayer');
player.pause();
}
function reset(){
pauseAudio();
nowPlaying = 0;
isPlaying = false;
// Unpress the button
}
// you can easily fill in the rest.
For understanding the audio control in HTML5 see this for an overview at w3schools, and this as an example on the same website.
Also note friendly remark: Javascript uses camelCase as a convention and not snake_case as in Python.

Make stop audio button

So I have code that looks like this. I press the button and an mp3 plays. But I can't seem to find a way to make a stop button for this and was hoping y'all could help me.
Name of Song 1
Name of Song 2
var audios =
Array.prototype.map.call(document.getElementsByClassName("buttons")
, function (el) {
var audio = new Audio();
var src = el.id + ".mp3";
el.onclick = function () {
audio.src = src;
audio.play();
};
return audio;
});
I tried
function stopmusic() {
audio.pause();
}
document.getElementById('stopbuttons').addEventListener('click', stopmusic);
and
function stopmusic() {
audios.forEach(audio=>audio.pause());
audios.forEach(audio=>audio.currentTime = 0.0);
audios.forEach(audio=>audio.src = "");
}
document.getElementById('stopbutton').addEventListener('click', stopmusic);
but couldnt get it to work
use audio.pause(); to stop the audio

Play video if no other video playing

Hi I have a page with multiple small videos which can be played by clicking on the covering image. How can I stop them playing onclick if there is already one playing? My script is as follows
function PlayVideo(aid, vid)
{
var myVideo = document.getElementsByTagName("video");
if (myVideo.paused) {
document.getElementById(vid).style.display = "block";
document.getElementById(vid).play();
document.getElementById(aid).style.display = "none";
document.getElementById(vid).addEventListener('ended', myHandler, false);
function myHandler(e) {
if (!e) {
e = window.event;
}
document.getElementById(vid).style.display = "none";
document.getElementById(vid).load();
document.getElementById(aid).style.display = "block";
}
} else {
alert("this is an alert");
return false;
}
}
Works fine without the if/else statement but any click starts the movie and then several movies are playing at once how do I define the parameters so that IF any video is playing then a new one will not start.
myVideo is a NodeList, you have to check the value of each video.
var allVideos = document.getElementsByTagName("video");
var areAllPaused = true;
for(var i=0; i < allVideos.length; i++) {
if (!allVideos[i].paused) {
areAllPaused = false;
}
}
you could just use a flag to check, ie
var videoIsPlaying = false;
function playVideo () {
if(videoIsPlaying){
//dont play video
}else{
//play video and set to true
videoIsPlaying = true;
}
}
you'd have to set it on pause etc
document.getElementsByTagName() will return an array with all the video elements in it. To check if any of them is playing you need to loop through the array and check whether any video is playing:
var anyPlaying=false;
for(var i=0;i<myVideo.length;i++){
if(!myVideo[i].paused){
anyPlaying=true;
}
}
if(!anyPlaying){
//...
}else{
return false;
}

Categories