Play (and replay) a sound on safari mobile - javascript

I need to play a sound when a new message appears on a website. It works fine on Chrome and Safari but I can't make it work on Safari mobile.
I saw that the sound has to be initialised with a user action so I tried that:
var sound = new Audio('./path/to/my/sound.mp3');
var hasPlayed = false;
$('body').bind('click touchstart', function() {
sound.load();
});
sound.addEventListener('play', function() {
hasPlayed = true;
});
var playSound = function() {
if(hasPlayed) {
sound.currentTime = 0;
}
sound.play();
}
Unfortunately, the sound still don't play. I also tried with the Buzz library, and the issue is the same.
So, the question is : how can I play a sound programmatically on mobile browsers ?

First of all: HTML5 audio support in Mobile Safari on iOS (5.01, 5.1) is rather limited. But I have managed to get some small 'event type' sounds working in my iPad 2 web apps. Since you are talking about only one sound file for your app, you don't have to fall back on audio sprites tricks (i.e. merging multiple MP3's into one MP3 file and changing the play position within the merged file depending on the sound you want to be played).
As you have noticed, you cannot play audio automatically in Mobile Safari, i.e. without the user clicking on some element. Technically speaking, the audio must be played (not loaded) in the same call stack as a click event. But you will probably experience a 0,5 second delay then, when Mobile Safari creates the audio object. Here is a solution to this 'problem':
At the start of your app (while loading/initializing), add a click handler to the HTML document that starts playing your audio file as soon as the user clicks/taps anywhere in the app. This will force Safari to start loading the audio.
Listen for the 'play' event that is triggered when the audio is ready to be played, and immediately pause.
Now start playing the audio (without delay) again when you need it.
Here is some quick JavaScript code:
function initAudio() {
var audio = new Audio('./path/to/my/sound.mp3');
audio.addEventListener('play', function () {
// When the audio is ready to play, immediately pause.
audio.pause();
audio.removeEventListener('play', arguments.callee, false);
}, false);
document.addEventListener('click', function () {
// Start playing audio when the user clicks anywhere on the page,
// to force Mobile Safari to load the audio.
document.removeEventListener('click', arguments.callee, false);
audio.play();
}, false);
}

For those that are coming across this problem and the solution by Jeroen is not working here is a solution that works and ensures the proper scoping is correctly enforced.
Make sure initAudio is called on page load. I.e. in your Init function or for jquery inside the document.ready ($(function(){});)
function initAudio(){
var audio = new Audio('./path/to/my/sound.mp3');
var self = this;
//not sure if you need this, but it's better to be safe
self.audio = audio;
var startAudio = function(){
self.audio.play();
document.removeEventListener("touchstart", self.startAudio, false);
}
self.startAudio = startAudio;
var pauseAudio = function(){
self.audio.pause();
self.audio.removeEventListener("play", self.pauseAudio, false);
}
self.pauseAudio = pauseAudio;
document.addEventListener("touchstart", self.startAudio, false);
self.audio.addEventListener("play", self.pauseAudio, false);
}

Related

How to make audio playback on work on mobile?

On desktop browsers im able to playback audio however, on mobile it doesnt playback any audio.
Im not getting any errors in the console either.
How can i make audio playback work on mobile?
function initAudio(){
var audio, dir, ext, mynoteslist;
dir = "audio/";
ext = ".mp3";
// Audio Object
audio = new Audio();
audio.src = dir+ext;
var arr = document.getElementsByClassName("mynoteslist");
for (var k=0; k<arr.length; k++){
arr[k].addEventListener("change", changeNote);
}
// Functions
function changeNote(event){
audio.src = dir+event.target.value+ext;
audio.play();
}
}
window.addEventListener("load", initAudio);
Many mobile devices will not play audio (or video if it has a soundtrack and is not muted) unless as a direct result of a user gesture.
For example for an Apple mobile device
the call to video.play(), for example, must have directly resulted from a handler for a touchend, click, doubleclick, or keydown event
You will probably therefore have to get the user to click or touch or sense a key down and use that event to play the audio. It seems that a change event will not be enough.

Vimeo API. Trouble with SetVolume method

I'm using Vimeo api in my project, but I have a problem with volume setting.
If I do so:
// Create the player
var player = new Vimeo.Player('video2', options);
//Ready event
player.ready().then(function() {
player.play();
});
Everything works, but without sound.
However, if I do so:
// Create the player
var player = new Vimeo.Player('video2', options);
//Ready event
player.ready().then(function() {
player.play();
player.setVolume(0.5);
});
The video does not play, and the screen hangs his screensaver.
What could be the problem?
Essentially by calling play when the video is ready, you are attempting to autoplay. However, this volume problem occurs because browsers no longer allow autoplay with sound (especially Chrome). You can read more about this on our Help article as well.
Therefore, it is impossible to programmatically play a video with volume without a user clicking/interacting with the video first. Only afterwards will a call to setVolume work.

safari browser doesn’t support HTML5 audio tag in ipad/iphone,Android

I am working on a project based on jquery animation its animation works fine on desktop (Firefox,chrome,opera,IE) also support HTML 5 audio tag but in Ipad/iphone/ Android safari audio tag doesn’t support.Its works fine on Ipad/iphone/ Android firefox.i have searched it in many forum don’t get desire Result. I have used this function :
function playmusic(file1,file2)
{
document.getElementById('music11').innerHTML='<audio id="music1"><source src="'+file1+'" type="audio/ogg"><source src="'+file2+'" type="audio/mpeg"></audio>';
$("#music1").get(0).play();
}
I have called function like : playmusic(2.ogg','2.mp3');
If I give autoplay in audio tag it works but play method not working and I have to use play method as in my application needs sound in particular event see the link
http://solutions.hariomtech.com/jarmies/
I have also changed my function and give direct audio tag in div and call function the same problem I face as I mentioned above. I need sound play in background without any click.if I use auto play method so it play sound only one time but I need sound multiple time on event.
Try to add an autoplay attribute on the audio tag:
function playmusic(file1, file2) {
document.getElementById('music11').innerHTML='<audio autoplay id="music1"><source src="'+file1+'" type="audio/ogg"><source src="'+file2+'" type="audio/mpeg"></audio>';
}
I would however recommend building a proper element and insert that into the DOM - something like this:
function playmusic(file1, file2) {
var audio = document.createElement('audio');
audio.preload = 'auto';
audio.autoplay = true;
if (audio.canPlayType('audio/ogg')) {
audio.src = file1;
}
else if (audio.canPlayType('audio/mpg')) {
audio.src = file2;
}
document.getElementById('music11').appendChild(audio);
}

Audio is still playing while minimize iPad browser safari

I have developed game is html5,Jquery, Javascript where I need to preload several audios. These audios are playing one by one but, when I minimize iPad then audio is still paying.
Can any body help to pause an audio while browser is going to minimize. And audio should play when browser comes to foreground.
I'm about halfway there to getting you a full solution. Here's what I have so far:
var audio = document.getElementsByTagName('audio')[0];
window.onpageshow = function() {
audio.play();
}
window.onpagehide = function() {
audio.pause();
}
So, as long as your on the app tab when you close Safari, it will pause the audio. And play it when you start back up. It doesn't stop when you change tabs.
If your app is apple-mobile-web-app-capable, this will trigger onpageshow when you open the app using the homescreen button, and will pause it when you close it. It doesn't pause exactly, since opening it back up forces it to start from the beginning. You'd have to capture where you were in the track using localStorage or something and then set the currentTime to that when you open it back up.
Looks like you'll be able to use the Visibility API in iOS 7 according to caniuse.com
Just for history's sake, I'm going to at least state some other things I tried.
window.onblur
using requestAnimationFrame with a setTimeout (this worked on desktops, but not iOS)
var t;
requestAnimationFrame(function checkWindow() {
if ( audio.paused ) {
audio.play();
}
clearTimeout(t);
t = setTimeout(function() {
audio.pause();
}, 32);
});
I recommend you use the page visibility API, which gives you an event that tells you when a page's visibility changes.
function handleVisibilityChange() {
if (document.hidden){
stopAllSounds();
}else{
playAllSounds();
}
}
document.addEventListener("visibilitychange", handleVisibilityChange, false);
stopAllSounds and playAllSounds will be defined as you see fit, but this event will fire when Safari is minimized and maximized. It works on Android devices and all modern platforms
Hopefully I am not late to answer it. I found the following solution which works in desktop and ios devices (haven't checked in android yet)
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
// do work
your_audio.pause();
break;
case "focus":
// do work
your_audio.play();
break;
}
}
$(this).data("prevType", e.type);
})
PS: your_audio is a variable, you have to define it.
I found this solution here

Play audio from a direct link

I'm working on a mobile device running iOS.
I have a DIRECT download link to an audio file (when I open it on desktop the download starts immediately). I try this but it plays only one time.
<script>var audio = new Audio("'+downloadUrl+'");</script> <button onclick="audio.play();">Play</button>
I also try to catch it with an <iframe> but it plays only one time.
When I use <audio> ,"streaming" appears and I have the same problem :
I think it's because my file is not saved on my phone. So how can I fix it, so that it plays as required.
Thanks in advance,
Let's take a look at the HTMLMediaElement DOM interface and Media Events
var audio = new Audio(downloadUrl);
audio.addEventListener('ended', function () {
audio.currentTime = 0; // seek to position 0 when ended playing
/* // alternatively, not sure about compatibility
audio.fastSeek(0);
*/
});
If you wanted it to loop rather than be playable again, set loop to true instead.

Categories