HTML5 Audio play two sounds in IOS - javascript

i want to play 2 sounds in ios and since it could not be done, i defined 2 audio objects.
i start playing the first sound and when want to play the second, i pause the first and wait till the second end, then i resume playing the first from the point it reached.
you can check the following code, if i remove the alert("test"); the first audio start playing from zero and so current time don't work!
kindly help.
Thanks,
var PlayedTime = 0; ; //in seconds
var AudioObj;
var audioType = '.mp3';
var isResume = false;
$(document).ready(function () {
if (!!AudioSound.canPlayType('audio/ogg') === true) {
audioType = '.ogg' //For firefox and others who do not support .mp3
}
AudioObj = document.getElementById('AudioSound');
document.getElementById('AudioSound').addEventListener('ended', function () {
resume();
});
});
function play1() {
AudioObj.src = "Images/Sound1" + audioType;
AudioObj.load();
}
function play2() {
PlayedTime = AudioObj.currentTime;
AudioObj.pause();
AudioObj.src = "Images/Sound2" + audioType;
AudioObj.load();
AudioObj.play();
}
function resume() {
isResume = true;
AudioObj.pause();
AudioObj.src = "Images/Sound1" + audioType;
AudioObj.load();
}
function JumpAudio() {
AudioObj.currentTime = 36;
}
function DataLoadedtoPlay() {
AudioObj.play();
if (isResume) {
isResume = false;
try {
alert("test");
AudioObj.currentTime = PlayedTime;
}
catch (e) {
alert("catch");
}
}
}
<div id="containerAud">
<audio id="AudioSound" onloadeddata="DataLoadedtoPlay()"></audio>
</div>
<input type = "button" onclick="play1()" value="click1"/>
<input type = "button" onclick="play2()" value="click2" />
<input type = "button" onclick="JumpAudio()" value="JumpAudio" />
</div>

Related

Unable to pause audio after eventListener end

When first loading the code, the pause button works fine, it pauses the audio and changes the HTML class of the button inside, the button continues to work after using the previous/next buttons to go to another song, however after the eventListener is triggered the pause button stops working, it doesn't pause the songs but the HTML inside still changes.
Edit: After a little bit of further debugging I found that the pause button is only able to pause the first time a track is loaded, once the audio.addEventListener('ended', nextTrack); is triggered it is unable to pause/play any audio.
let audio = new Audio;
let playing = false;
let playpause = document.getElementById('play-pause');
let root = document.documentElement;
let songname = document.getElementById('name');
let next = document.getElementById('next');
let prev = document.getElementById('previous');
let index = 0;
songlist = [
{"name":"Love Again"
,"artist":"The Kid LAROI",
"path":"resources/music/love-again.mp3",
},
{
"name":"Always Do",
"artist":"The Kid LAROI",
"path":"resources/music/always-do.mp3",
},
{
"name":"Bye Bye",
"artist":"Juice WRLD",
"path":"resources/music/bye-bye.mp3",
},
{
"name":"Understand",
"artist":"BoyWithUke",
"path":"resources/music/understand.mp3",
}
]
function progress_animation(){
var currentTime = audio.currentTime;
var duration = audio.duration;
$('#progbar').stop(true, true).animate({ 'width': (currentTime + .25) / duration * 100 + '%' }, 250, 'linear');
window.requestAnimationFrame(progress_animation);
};
function load(index){
songname.textContent = `${songlist[index].artist} - ${songlist[index].name}`;
audio.src = songlist[index].path;
audio.load()
};
audio.addEventListener('ended', nextTrack);
$('#play-pause').click(function (){
if (!playing) {
Play()
playing = true
} else {
Pause()
playing = false
}
});
function nextTrack(){
if (index < songlist.length - 1) {
index++;
} else {
index = 0;
}
load(index);
};
function prevTrack(){
if (index > 0) {
index--;
} else {
index = songlist.length - 1;
}
load(index);
};
function Play() {
audio.play();
playing = true;
playpause.innerHTML = '<i class="fa-solid fa-pause"></i>';
};
function Pause() {
audio.pause()
playing = false;
playpause.innerHTML = '<i class="fa-solid fa-play"></i>';
};
The pause button still changes its HTML class and sets the "playing" variable to false/true depending on the state of "playing" but doesn't actually pause the song

Vanilla JS image slideshow play/pause button

My play/pause button works the first time I press pause and the first time I press play. But after that if I want to pause the slideshow again, it just plays the slideshow at a faster speed and I am no longer able to pause it.
I am thinking maybe it is to do with the fact I have two separate functions: one for the play/pause button icon toggle, and another for the actual play pause behaviour? (update: this has now been fixed, but still doesn't work)
Sorry, I am struggling with javascript, I have a lot to learn.
My script:
const playPause = document.querySelector('.pause');
let slideId;
// FUNCTION TO MOVE TO NEXT SLIDE
const moveToNextSlide = () => {
slides = getSlides();
if (index >= slides.length - 1) return;
index++;
slideGroup.style.transform = `translateX(${-slideWidth * index}px)`;
slideGroup.style.transition = '.8s';
}
// FUNCTION TO START SLIDESHOW
const startSlide = () => {
slideId = setInterval(() => {
moveToNextSlide();
}, interval);
playing = true;
};
// START AUTOMATIC SLIDESHOW UPON ENTERING THE PAGE
startSlide();
//PLAY PAUSE BUTTON - slideshow start/stop
playPause.addEventListener('click', () => {
if(!slideId) {
slideId = startSlide();
console.log('started');
} else {
clearInterval(slideId);
slideId = null;
console.log('stopped');
}
});
//PLAY PAUSE BUTTON - image change
function toggle(button) {
if (button.className != 'pause') {
button.src = 'img/pause.png';
button.className = 'pause';
}
else if (button.className == 'pause') {
button.src = 'img/play.png';
button.className = 'play';
}
return false;
}
HTML:
<input type='image' src='img/pause.png' class='pause' onclick='toggle(this);' />
This is what the console looks like when I try to pause the slideshow for a second time:
There are some details in your code that are missing and would be helpful to have, but I guess that you can get rid of the onclick handler and attach two event listeners:
let slideId;
// FUNCTION TO START SLIDESHOW
const startSlide = () => {
let interval = 2000; // using just as sample
playing = true;
return setInterval(() => {
console.log('moveToNextSlide();') // replaced just to test without missing code
}, interval);
};
//PLAY PAUSE BUTTON - slideshow start/stop
playPause.addEventListener('click', () => {
if(!slideId) {
slideId = startSlide();
console.log('started');
} else {
clearInterval(slideId);
slideId = null;
console.log('stopped');
}
});
//PLAY PAUSE BUTTON - image change
playPause.addEventListener('click', function toggle() { // the arrow function would not work in this case
var button = this;
if (button.className != 'pause') {
button.src = 'img/pause.png';
button.className = 'pause';
}
else if (button.className == 'pause') {
button.src = 'img/play.png';
button.className = 'play';
}
return false;
});

How to pause previous audio function?

When I press the button, I want to play a song, when I press the second song a second time, and when the third one, the cycle repeats again, but the first song is shorter than the second one, and if you click many times, the long song plays simultaneously with its other copy. Is it possible to stop the previous music and move on to another?
Html:
< a id="Play">test< / a>
Script:
window.onload=function(){
let number = 0;
var t;
document.getElementById('Play').addEventListener('click',function(){
let audio = new Audio();
if ( number == 0 ) {
audio.src = '/assets/sound/test.mp3';
number = 1;
}
else
if ( number == 1 ) {
audio.src = '/assets/sound/curious&loony.mp3';
number = 0;
}
audio.autoplay = true;
});
}
sound.pause();
sound.currentTime = 0;
Use this for pause audio
Found a way.
How to:
<script>
var i = 1, player = new Audio();
player.src = "/assets/sound/sound1.mp3";
document.querySelector('#play-button').addEventListener('click', function(e) {
e.preventDefault();
if (i === 1) {
player.src = "/assets/sound/sound1.mp3";
i = 0;
} else if (i === 0) {
player.src = "/assets/sound/sound2.mp3";
i = 1;
}
player.play();
});
</script>
Play me harder

can't choose seek time of a video from a scroll bar

I want to use a video tag and control it with javascript,
but it doesn't work as I want.
function vidplay(evt) {
if (video.src == "") { // inital source load
getVideo();
}
button = evt.target; // get the button id to swap the text based on the state
if (video.paused) { // play the file, and display pause symbol
video.play();
button.textContent = "||";
} else { // pause the file, and display play symbol
video.pause();
button.textContent = ">";
}
}
// load video file from input field
function getVideo() {
var d = document.getElementById('a4').innerHTML; // video file name
// var fileURL = document.getElementById("videoFile").value; // get input field
var fileURL = d; // get input field
if (fileURL != "") {
video.src = fileURL;
video.load(); // if HTML source element is used
document.getElementById("play").click(); // start play
} else {
errMessage("Enter a valid video URL"); // fail silently
}
}
var d in function getVideo() is like "http://192.168.44.112/~/~.mp4"
This video was uploaded on mongoDB and I want to use it.
The video works well but the seek bar doesn't work at all,
it only seeks to time 0.
document.getElementById("rew").addEventListener("click", function() {
setTime(-10);
}, false);
document.getElementById("fwd").addEventListener("click", function() {
setTime(10);
}, false);
function setTime(tValue) {
// if no video is loaded, this throws an exception
try {
if (tValue == 0) {
video.currentTime = tValue;
} else {
video.currentTime += tValue;
}
} catch (err) {
// errMessage(err) // show exception
errMessage("Video content might not be loaded");
}
}
And when i use setTime() function, it goes to seek time 0, while I want to seek at the time corresponding to where I click .
How can I do it ?
I made this quick example that you can test & study, then afterwards you can just apply a similar logic to your above shown code. Hope it helps your problem.
<video id="myVid" width="640" height="480" controls>
<source src="yourVideoFile.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<script>
tValue = 0; //start at zero
myVid.addEventListener('seeking', function(e){ tValue = myVid.currentTime })
function setTime_FWD()
{
try
{
if (tValue >= myVid.duration) { tValue = myVid.duration; }
else { tValue += 10; myVid.currentTime = tValue; }
}
catch (err) { errMessage("Video content might not be loaded"); }
}
function setTime_RWD()
{
try
{
tValue -= 10;
if (tValue <= 0) { myVid.currentTime = tValue = 0; }
else { myVid.currentTime = tValue; }
}
catch (err) { errMessage("Video content might not be loaded"); }
}
</script>
<br><br>
<button onclick="setTime_RWD()"> << </button>
<button onclick="setTime_FWD()"> >> </button>

Display diffrent image depending on timer

I'm trying to display a different image depending on the timer's result and can't find a way through. So far I have a start and stop button, but when I click stop, I want to use the value the timer is on and display an image(on alertbox or the webpage itself) depending on that value.
if( timer =>60){
img.src("pizzaburnt.jpg");
}elseif (timer <=30){
img.src("pizzaraw.jpg");
}
else{
img.src("pizzaperfect.jpg
}
///Time
var check = null;
function printDuration() {
if (check == null) {
var cnt = 0;
check = setInterval(function () {
cnt += 1;
document.getElementById("para").innerHTML = cnt;
}, 1000);
}
}
//Time stop
function stop() {
clearInterval(check);
check = null;
document.getElementById("para").innerHTML = '0';
}
**HTML**
<td>
Timer :<p id="para">0</p>
</td>
Any advice or dicussion would be great, thanks.
Something like this would work better and it's more compact:
var img = document.getElementById("image");
var imageSrcs = ['pizzaRaw.jpg', 'pizzaPerfect.jpg', 'pizzaBurnt.jpg'];
var imageIndex = 0;
var interval = setInterval(animate, 30000); //change image every 30s
var animate = function() {
//change image here
//using jQuery:
img.src(imageSrcs[imageIndex]);
imageIndex++; //move index for next image
if (imageIndex == imageSrcs.length) {
clearInterval(interval); //stop the animation, the pizza is burnt
}
}
animate();
Reason you wouldn't want to use an increment variable and a 1 second timer is because your just conflating your logic, spinning a timer, and making a bit of a mess when all you really want is the image to change every 30 seconds or whenever.
Hope this helps.
You need an <img> tag in your HTML like this:
<html>
<body>
Timer: <p id="para">0</p>
Image: <img id="image" />
</body>
</html>
And the Javascript code will be like:
var handle;
var timerValue = 0;
var img = document.getElementById( "image" );
var para = document.getElementById("para");
function onTimer() {
timerValue++;
para.innerHTML = timerValue;
if ( timerValue >= 60 ) {
img.src( "pizzaburnt.jpg" );
}else if ( timer <= 30 ) {
img.src( "pizzaraw.jpg" );
} else {
img.src("pizzaperfect.jpg" );
}
}
function start () {
if ( handle ) {
stop();
}
timerValue = 0;
setInterval( onTimer, 1000 );
}
function stop () {
if ( handle ) {
clearInterval ( handle );
}
}
Please make sure that these 3 files are in the same directory as your HTML file:
pizzaburnt.jpg
pizzaraw.jpg
pizzaperfect.jpg

Categories