Play/pause HTML audio doesn't work on iOS - javascript

I've implemented an html audio into my website with play/pause button via JS. Works perfect on all desktop and mobile devices apart from iOS.
This is not an autoplay, so I don't think it is braking any iOS policies?
This is a code I'm using.
P.S: tried searching on stackoverflow but found nothing that works.
<style>
#demo {
width: 60px;
height: 60px;
outline: none;
}
</style>
<button onclick="Play()" id="demo"></button>
<audio id="player" preload="auto">
<source src="https://s3.eu-central-1.amazonaws.com/radmitry/Yoshio_Chino-We_Pray_For_Japan.mp3">
</audio>
<script>
var audio = document.getElementById("player");
audio.volume = 0.5;
var butn = document.getElementById("demo");
butn.style.background = "url(https://uploads-ssl.webflow.com/5acdf398c6f3e7252e9a31b9/5ad9f901d9a651ff58dad03b_play.svg) no-repeat";
function Play() {
if(audio.paused) {
audio.play();
butn.style.background = "url(https://uploads-ssl.webflow.com/5acdf398c6f3e7252e9a31b9/5ad9f8b88fb8e56097aa04ca_pause.svg) no-repeat";
}
else {
audio.pause();
butn.style.background = "url(https://uploads-ssl.webflow.com/5acdf398c6f3e7252e9a31b9/5ad9f901d9a651ff58dad03b_play.svg) no-repeat";
}
}
</script>

Related

Play multiple audio tracks sequentially, not simultaneously

I'm trying to use the <audio> tag, and I want to have as many tracks playing as I add. But now they play at the same time, can I somehow make them play sequentially?
<audio id="audio1" preload="" autoplay="" loop="" type="audio/mp3" src="music/mus1.mp3"></audio>
<audio id="audio2" preload="" autoplay="" loop="" type="audio/mp3" src="music/mus.mp3"></audio>
<div id="pp" style="cursor: pointer;" onclick="pVid();"><img src="img/heart.png"></div>
<script type="text/javascript">
function pVid() {
var audio1 = document.getElementById("audio1");
var audio2 = document.getElementById("audio2");
audio1.paused ? audio1.play() : audio1.pause();
audio2.paused ? audio2.play() : audio2.pause();
}
</script>
I found one solution, it works but not the way I want
var sounds = new Array(new Audio("music/mus1.mp3"), new Audio("music/mus.mp3"));
var i = -1;
pVid();
function pVid() {
i++;
if (i == sounds.length) return;
sounds[i].addEventListener('ended', pVid);
sounds[i].play();
}
Here everything just plays right away, but I want to be able to play the tracks myself through the button and pause at any time. This is done in the first version, but there all the tracks play at the same time
Use audio events as much as possible. We can use freesound.org for testing.
let sounds = new Array(new Audio("https://freesound.org/data/previews/46/46992_514283-lq.mp3"),
new Audio("https://freesound.org/data/previews/610/610823_13156161-lq.mp3"),
new Audio("https://freesound.org/data/previews/92/92005_1499847-lq.mp3"), new Audio("https://freesound.org/data/previews/46/46992_514283-lq.mp3"),
new Audio("https://freesound.org/data/previews/610/610823_13156161-lq.mp3"),
new Audio("https://freesound.org/data/previews/92/92005_1499847-lq.mp3"));
let current = random(0);
let paused = true;
// set event handlers on all audio objects
for (let s of sounds) {
s.addEventListener('ended', ended);
s.addEventListener('play', play);
s.addEventListener('pause', pause);
}
updateVolume()
// handle button click
function playPause() {
if (paused) {
sounds[current].play();
btn.innerText = 'pause';
paused = false;
} else {
sounds[current].pause();
btn.innerText = 'play';
paused = true;
}
}
function ended(e) {
document.getElementById(current + '').classList.remove('playing');
document.getElementById(current + '').classList.remove('paused');
/*i++;
if (i >= sounds.length) //loop
i = 0;
*/
current = random(current); // shuffle
paused = true;
playPause();
}
function play() {
document.getElementById(current + '').classList.add('playing');
document.getElementById(current + '').classList.remove('paused');
}
function pause() {
document.getElementById(current + '').classList.add('paused');
document.getElementById(current + '').classList.remove('playing');
}
function random(i) {
let next = i;
while (next == i)
next = Math.floor(Math.random() * sounds.length);
return next;
}
function updateVolume() {
for (let s of sounds) {
s.volume = volume.value;
}
}
#list {
margin-top: 1rem;
border: 1px solid gray;
width: 100px;
}
#controls {
position: fixed;
right: 2rem;
top: 1rem;
width: 50px;
}
#volume {
width: 150px;
height: 20px;
transform-origin: 75px 75px;
transform: rotate(-90deg) translateY(50%);
}
.playing {
background-color: lightblue;
}
.paused {
background-color: wheat;
}
<Button id=btn onClick='playPause()'>play</Button>
<div id=list>
<div id='0'>Guitar</div>
<div id='1'>Drum</div>
<div id='2'>Violin</div>
<div id='3'>Guitar</div>
<div id='4'>Drum</div>
<div id='5'>Violin</div>
</div>
<div id=controls>
<label for="volume">Volume</label><br>
<input id=volume type="range" id="volume" name="volume" min="0" max="1" step='.1' value='.5' onInput='updateVolume()'>
</div>
I don't know why no one mentioned the onended event
<audio id="aud1" onended="playaud2()" src="whatever.mp3"> <!--first audio-->
<audio id="aud2" src="whatever.mp3"> <!--second audio-->
<script>
//the onended event calls a function when the audio finishes playing
function playaud2() {
document.getElementById("aud2").play()}
</script>
As simple :)
Audio files
For testing, I used a few free sound-effects audio files from https://www.freesoundeffects.com.
To make it work in all browsers it is recommended by w3c to use the <audio>-tag with <source> tags.
Solution
I added some arbitrary sound files and buttons. The buttons will reset all the audios that are currently playing then play the sounds in the data-track attributes.
data-track syntax:
track-a // will play track a
track-a;track-b // will play track a followed by track b
track-a+track-b // will play track a and b simultaniously
track-a+track-b;track-c // as above but add track c to the end
You could do something like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
audio {
display: block;
}
</style>
<script defer type="application/javascript">
let activeTimeout;
function init(player) {
player.innerHTML = `play ${player.dataset.label}`;
player.addEventListener('click', clickHandler);
}
function reset(audio) {
clearTimeout(activeTimeout);
audio.pause();
audio.currentTime = 0;
}
function dequeue(tracks) {
console.log("Queue:", tracks);
if (tracks.length >= 1) {
const track = tracks.pop();
const multiTrack = track.split('+');
let maxDuration = 0;
multiTrack.forEach((it) => {
const audio = document.querySelector(`[data-audio="${it}"]`);
maxDuration = Math.max(maxDuration, audio.duration);
audio.play();
});
activeTimeout = setTimeout(() => {
dequeue(tracks);
}, maxDuration * 1000);
}
}
function clickHandler(e) {
const allAudios = document.querySelectorAll('[data-audio]');
const trackAttr = this.dataset.track;
const tracks = trackAttr.split(';');
if (tracks) {
allAudios.forEach(reset);
dequeue(tracks.reverse()); // reverse to make the pop-operations faster
} else {
console.log('No track defined!');
}
}
window.addEventListener('load', function() {
const players = document.querySelectorAll('[data-player]');
players.forEach((it) => init(it));
});
</script>
</head>
<body>
<audio data-audio="applause" controls="controls" preload="preload">
<source src="https://www.freesoundeffects.com/files/mp3_426807.mp3" type="audio/mp3"></source><!-- replace with your audio file -->
</audio>
<audio data-audio="bark" controls="controls" preload="preload">
<source src="https://www.freesoundeffects.com/files/mp3_89478.mp3" type="audio/mp3"></source><!-- replace with your audio file -->
</audio>
<audio data-audio="chirp" controls="controls" preload="preload">
<source src="https://www.freesoundeffects.com/files/mp3_89489.mp3" type="audio/mp3"></source><!-- replace with your audio file -->
</audio>
<button data-player data-label="bark!" data-track="bark" />
<button data-player data-label="chirp!" data-track="chirp" />
<button data-player data-label="applause!" data-track="applause" />
<button data-player data-label="applause then bark!" data-track="applause;bark" />
<button data-player data-label="bark then chirp then bark again!" data-track="bark;chirp;bark" />
<button data-player data-label="applause then chirp!" data-track="applause;chirp" />
<button data-player data-label="applause with chirp then bark!" data-track="applause+chirp;bark" />
</body>
</html>
Yes, you can check if you have an element with a simple truthy/falsy check:
if (!slider) return;

How to create a video and a canvas then draw it to the canvas?

I am having trouble getting this video element to add to the canvas it plays it creates inside the canvas but will not draw to the canvas. Can anyone explain to me where I have gone wrong please?
<!DOCTYPE html>
<html>
<style>
canvas {
border: 1px solid black;
}
</style>
<body>
<div id="popUpCanvas">
</div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var videoCanvas = document.createElement("Canvas");
var video = document.createElement("Video");
var source = document.createElement("Source");
var context = videoCanvas.getContext('2d');
videoCanvas.setAttribute('class', 'CanvasVideo');
videoCanvas.setAttribute('id', 'CanvasVideo');
video.setAttribute('class', 'videoCanvas');
video.setAttribute('id', 'videoCanvas');
video.setAttribute('controls', '');
video.setAttribute('autoplay', '');
source.setAttribute('class', 'videoSource');
source.setAttribute('id', 'videoSource');
source.setAttribute('src', 'http://www.imgur.com/mClEpxu.mp4');
source.setAttribute('type', 'video/mp4');
video.appendChild(source);
videoCanvas.appendChild(video);
context.drawImage(video,0,0,100,100);
document.getElementById("popUpCanvas").appendChild(videoCanvas);
}
</script>
</body>
</html>
You don't need a canvas to show a video on HTML5, this is an example of the working code:
It will have the canvas border around the video, but there is no need to use the canvas element.
<!DOCTYPE html>
<html>
<style>
.CanvasVideo {
border: 1px solid black;
width: 300px;
height: 300px;
}
video {
height: inherit;
width: inherit;
}
</style>
<body>
<div id="popUpCanvas">
</div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var videoCanvas = document.createElement("Div");
var video = document.createElement("Video");
var source = document.createElement("Source");
videoCanvas.setAttribute('class', 'CanvasVideo');
videoCanvas.setAttribute('id', 'CanvasVideo');
video.setAttribute('class', 'videoCanvas');
video.setAttribute('id', 'videoCanvas');
video.setAttribute('controls', '');
video.setAttribute('autoplay', '');
source.setAttribute('class', 'videoSource');
source.setAttribute('id', 'videoSource');
source.setAttribute('src', 'http://www.imgur.com/mClEpxu.mp4');
source.setAttribute('type', 'video/mp4');
video.appendChild(source);
videoCanvas.appendChild(video);
document.getElementById("popUpCanvas").appendChild(videoCanvas);
}
</script>
</body>
</html>
You need to update the canvas each frame so that the contents of the video appears in real time. This can be achieved with an Animation Frame:
requestAnimationFrame(updateVideo);
function updateVideo() {
if (!video.ended) requestAnimationFrame(updateVideo);
context.clearRect(0,0,100,100);
context.drawImage(video,0,0,100,100);
}
This function will be called before each frame so that it updates the video with the screen. Hope this helps.

How to make multiple playback buttons?

I have code for one button, how to do for multiple?
image example
I tried to get around all the elements, but the tracks played simultaneously.
http://codepen.io/anon/pen/mmyaQx
On jquery I did it, but I can not on native JavaScript.
window.onload = function(){
var myAudio = document.getElementById('my-audio');
var play = document.getElementById('play');
var pause = document.getElementById('pause');
var loading = document.getElementById('loading');
var bar = document.getElementById('bar');
function displayControls() {
loading.style.display = "none";
play.style.display = "block";
}
// check that the media is ready before displaying the controls
if (myAudio.paused) {
displayControls();
} else {
// not ready yet - wait for canplay event
myAudio.addEventListener('canplay', function() {
displayControls();
});
}
play.addEventListener('click', function() {
myAudio.play();
play.style.display = "none";
pause.style.display = "block";
});
pause.addEventListener('click', function() {
myAudio.pause();
pause.style.display = "none";
play.style.display = "block";
});
// display progress
myAudio.addEventListener('timeupdate', function() {
//sets the percentage
bar.style.width = parseInt(((myAudio.currentTime / myAudio.duration) * 100), 10) + "%";
});
}
#controls {
width: 80px;
float: left;
}
#progress {
margin-left: 80px;
border: 1px solid black;
}
#bar {
height: 20px;
background-color: green;
width: 0;
}
<audio id="my-audio">
<source src="http://jPlayer.org/audio/mp3/Miaow-07-Bubble.mp3" type="audio/mpeg">
<source src="http://jPlayer.org/audio/ogg/Miaow-07-Bubble.ogg" type="audio/ogg">
</audio>
<div id="controls">
<span id="loading">loading</span>
<button id="play" style="display:none">play</button>
<button id="pause" style="display:none" >pause</button>
</div>
<div id="progress">
<div id="bar"></div>
</div>
I do not know what you want to achieve, but it seems that you are trying to reinvent the wheel...
Do you know that you can enable controls on the HTML5 audio player? :)
<audio controls>
<source src="http://jPlayer.org/audio/mp3/Miaow-07-Bubble.mp3" type="audio/mpeg">
<source src="http://jPlayer.org/audio/ogg/Miaow-07-Bubble.ogg" type="audio/ogg">
</audio>
something like this will help you..
make function instead of window.onload and paremetrize it.. then call each in start function..
function start(){
buildOne( 'my-audio', 'play', 'pause', 'loading', 'bar' );
buildOne( 'my-audio2', 'play2', 'pause2', 'loading2', 'bar2' );
}
window.onload = start;
full example is here: http://codepen.io/mkdizajn/pen/ZKYwEQ?editors=1011

I need help getting autoplay to work via [getElementById]

My code: https://jsfiddle.net/m656xw8s/24/
I've been trying to get autoplay to work, can someone show me what the correct code would be? Using the code I provided. Using [getElementById]
var player = document.getElementById('player').autoplay; document.getElementById('player').innerHTML = true;
<button id="playButton" style="border:none; width: 200px; height: 200px; cursor: pointer; font-family:Tahoma; font-weight: bold;font-size:14px; background-color:red;color:blue;" onclick="
var player = document.getElementById('player').autoplay;
document.getElementById('player').innerHTML = true;
var player = document.getElementById('player').volume='1.0';
var button = document.getElementById('playButton');
var player = document.getElementById('player');
if (player.paused) {
playButton.style.backgroundColor = 'red';
player.play();
} else {
playButton.style.backgroundColor = 'red';
player.pause();
}">
</button>
<audio id="player" style="display:none;">
<source src='http://hi5.1980s.fm/;' type='audio/mpeg' />
</audio>
Set the autoplay then load.
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_av_prop_autoplay
Update:
document.getElementById('playButton').addEventListener('click', autoPlayToggle);
document.getElementById('autovolume_range').addEventListener('change', changeVol);
//Only getElementById once!
var player = document.getElementById("player");
var autoplaytext = document.getElementById("autoplay_text");
var autovolumetext = document.getElementById("autovolume_range");
//Boolean from localstorage to keep state of the player
var autoPlayOn = autoplaytext.value = (localStorage.getItem("keepAutoPlay") === "true");
var setVolumeOn = autovolumetext.value = parseFloat(localStorage.getItem("keepVolume"));
player.volume = setVolumeOn;
player.autoplay = autoPlayOn;
player.load();
//Force play if it dosen't autoplay after refresh
if (player.autoplay == true) {
player.play();
} else {
player.pause();
}
//Function
//When the user refreshes the page it will keep the autoplay state
function autoPlayToggle() {
if (player.paused) {
player.play();
player.autoplay = true;
} else {
player.pause();
player.autoplay = false;
}
//Show the state in a text box
autoplaytext.value = player.autoplay;
//Save updated state to your local disk
localStorage.setItem("keepAutoPlay", autoplaytext.value);
}
//Save state of volume
function changeVol() {
player.volume = this.value;
localStorage.setItem("keepVolume", this.value);
}
<button id="playButton" style="border:none; width: 200px; height: 200px; cursor: pointer; font-family:Tahoma; font-weight: bold;font-size:14px; background-color:red;color:blue;">
</button>
<audio id="player" style="display:none;" >
<source src='http://hi5.1980s.fm/;' type='audio/mpeg'/>
</audio>
AutoPlay: <input id="autoplay_text" />
AutoVolume: <input type="range" step="0.1" min="0.0" max="1.0" id="autovolume_range" />
https://jsfiddle.net/LeroyRon/dtnrdjd5/
You only need to add attribute auto play to your audio tag see the updated code below; Based on your code you are redeclaring player multiple times see the updated code below. Your auto play is triggered on button click based on your code, you may want to separate the javascript codes to the button and just trigger a method indicated on your button click event.
You will need to use removeAttribute to remove the autoplay from your audio element. I added the code on how to do it below.
//player declared outside of the audioPlay method to make it accessible inside the audioPlay method
var player = document.getElementById('player');
//auto play set outside playAudio method outside of the button click event method
player.setAttribute('autoplay', '');
//to set autoplay false uncomment the code below
//player.removeAttribute('autoplay');
//playAudio is triggered on button click event
function playAudio(){
player.setAttribute('volume', 1.0);
var button = document.getElementById('playButton');
if (player.paused) {
playButton.style.backgroundColor = 'red';
player.play();
} else {
playButton.style.backgroundColor = 'red';
player.pause();
}
}
<button id="playButton" style="border:none; width: 200px; height: 200px; cursor: pointer; font-family:Tahoma; font-weight: bold;font-size:14px; background-color:red;color:blue;" onclick="
playAudio()">
</button>
<audio id="player" style="display:none;">
<source src='http://hi5.1980s.fm/;' type='audio/mpeg' />
</audio>

overlay a link over a playing video at a specific time in a HTML page

I would like to know how to overlay a link over a playing video at a specific time in a HTML page.
We know Youtube does it easily, but I need to do so without Youtube. :)
I thank you all in advance.
There are many ways to do this.
Here is a simple one using setInterval. The link will shown in 3 seconds of the video.
var video = document.querySelector('video'),
link = document.querySelector('a'),
timer = document.querySelector('#timer');
setInterval(function() {
if (video.currentTime > 3 && video.currentTime < 6) {
link.style.display = 'block';
}
else {
link.style.display = 'none';
}
timer.textContent = video.currentTime;
}, 100);
.wrapper {
position:relative;
}
a {
position:absolute;
top:10px;
left:10px;
background:rgba(0,0,0,0.8);
color:#fff;
display:none;
}
<div class="wrapper">
<video width="320" height="240" controls>
<source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
</video>
Here is your link
</div>
<div>Current time: <span id="timer"></span></div>

Categories