Playing a MP3 with
var popsound = new Audio('http://gget.it/u1urz3zh/popsound.mp3'); popsound.load(); popsound.play();
doesn't work in Chrome for Android. According to this link , this is a feature, to not allow playback this way, ie without explicit user input.
I understand that this is done on purpose (to save mobile data for the user, mainly), but then how to make a website play a notification sound? There surely is a way to play notification sounds (notifications are popular on phone), how to do it?
If not possible, at least, how to know (with JS) if the browser will be allowed or not allowed to play sound with .play()
? (then it will be possible to show if sound notifications are available or not on the website)
Context : I'm creating a web chat service , then how to play a sound notification after a message is posted if I cannot use .play()
in Chrome for Android?
At least this trick allows to know in advance if media playback requires user gesture:
function mediaPlaybackRequiresUserGesture() {
var audio = document.createElement('audio');
audio.play();
return audio.paused;
}
I met the same problem in my app. My application usage scenario was like this:
1) click the button to show a table with information (user action)
2) show the table and refresh data in it by AJAX
3) play sound when data has been changed
Fortunatelly I had the user action (step 1) so I was able to "initiate" the sound by it and then play it by javascript without the user action needed. See the code.
HTML
<audio id="kohoutAudio">
<source src="views/images/kohout.mp3">
</audio>
<button id="btnShow">Show table</button>
Javascript
$("#btnShow").click(function () {
//some code to show the table
//initialize the sound
document.getElementById('kohoutAudio').play();
document.getElementById('kohoutAudio').pause();
});
function announceChange(){
document.getElementById('kohoutAudio').play();
};
You can add an audio element to the DOM and change it dynamically via javascript.
setTimeout(function() { document.getElementById('audio').src = 'http://gget.it/u1urz3zh/popsound.mp3'; document.getElementById('audio').load(); document.getElementById('audio').play(); }, 2000);
<audio id="audio"></audio>
Here is how I played sound in one of my web project, I had used JQuery, but you can modify it little bit to work in Javascript or instead use JQuery.
create a html tag audio and set the source of it.
<audio id="chatAudio"><source src="01.mp3" type="audio/mpeg"></audio>
and fire a play method of audio using JQuery.
$('#chatAudio')[0].play();
I am not sure if it works for you or not. but you can try this way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.