The code below works fine on desktop browsers (plays music). But when I try to open the site on any mobile device it doesn't work.
var music = new Audio("mscs/gamemusic.mp3");
function playmusic() {
music.controls = false;
music.loop = false;
music.autoplay = true;
document.body.appendChild(music)
}
I use it in a function when game starts:
function createnewgame() {
...
playmusic();
...
...
}
Does anyone know what's wrong?
Well, this is clearly a browser support issue. According to caniuse, the <audio> element (and js' Audio object is an interface used for it) has known support issues, including
iOS and Chrome on Android do not support autoplay as advised by the specification
and others. Not sure if this can be overcome by some library but since the limitation of autoplay was introduced by design, I wouldn't count on workarounds...
Instead of adding the var "music" to html body, you can try playing the audio directly from JavaScript.
function playmusic() {
music.play();
}
Some mobile browsers support automatic playback of audio, but ios, chrome and others require interactive actions to trigger the sound playback.You can try working with the mute attribute...enter link description here
Related
I use the html5 audio library Buzz to add sounds to a browser game. There is a toggle button to mute and unmute sound, which works good on desktop and Android devices. Unfortunately it seems like the audio tag is quite limited on IOS, so that I cannot mute audio in Mobile Safari (see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Introduction/Introduction.html):
On iOS devices, the audio level is always under the user’s physical control. The volume property is not settable in JavaScript. Reading the volume property always returns 1.
Do you know any workaround to control volume of html5 audio tags in Mobile Safari?
To add volume change support to iOS and not rewrite your entire app from html5 audio to web audio for that, you can combine these audio solutions via createMediaElementSource.
Please see more details at Mozilla website https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/createMediaElementSource
I always thought dynamic volume control and certainly crossfading, as we all know, is impossible. Apple has dictated that it be so. Except.... apparently the folk at Kodo Games (specifically Nicola Hibbert?) have pulled it off and made the code available to anyone. I just checked it on iOS 8. Fading and crossfading seem to work!
Check it out (new site that works): Getting Started with Web Audio API
It seems that you can set the muted property instead of updating the volume value. Works on iOS 15
/**
* Set volume of sound object
* #param volume
*/
setVolume (volume) {
const muted = volume === 0
// iOS workaround when volume is 0
this.sound.muted = muted
this.sound.volume = volume
}
I worked around this by simply stopping all sounds and setting a variable isMuted to true or false, so I can check this everywhere a sound is played:
// set the variable
var isMuted = false;
// toggle audio
function toggleMute() {
var toggleAudioBtn = $(".toggleAudio");
if (isMuted == false) {
sounds.stop();
isMuted = true;
toggleAudioBtn.css("background-image", "url('images/ui/btn_audio_mute.png')");
} else {
isMuted = false;
toggleAudioBtn.css("background-image", "url('images/ui/btn_audio.png')");
}
};
// for every sound check if sound is muted
if(isMuted == false) {
sound.play();
}
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.
Today I get started in appmobi. I was developing a small example to deal with sounds.
I just needed to create a handler to play and stop many sounds.
var audioOn = new Audio('sounds/11.mp3');
audioOn.play();
This code is working in the xdk simulator, also on android devices, but not in my Iphone 5.
The thing is, if I use tag it works on iphone, but I want to use javascript native api to deal with sounds and more.
I have been trying to deal with it with appmobi player library but it comes without controls to stop, resume etc, thats way I want to use native.
Here is part of javascript code :
<script type="text/javascript">
/* This function runs once the page is loaded, but appMobi is not yet active */
var init = function(){
var alarmButton = document.getElementById("alarmButton");
var on = false;
//var audioOn = new Audio('http://rpg.hamsterrepublic.com/wiki-images/3/3e/Heal8-Bit.ogg');
var audioOn = new Audio('sounds/11.mp3');
audioOn.addEventListener('ended', function() {
this.play();
}, false);
var but = function(){
alert("but");
alert(on);
alert(audioOn);
if(!on){
on = true;
audioOn.currentTime = 0;
audioOn.play();
}
else{
on = false;
audioOn.pause();
}
}
//alarmButton.addEventListener("click",but,false);
alarmButton.addEventListener("touchstart",but,false);
alarmButton.addEventListener("tap",but,false);
};
window.addEventListener("load",init,false);
/* This code prevents users from dragging the page */
var preventDefaultScroll = function(event) {
event.preventDefault();
window.scroll(0,0);
return false;
};
document.addEventListener('touchmove', preventDefaultScroll, false);
/* This code is used to run as soon as appMobi activates */
var onDeviceReady=function(){
//Size the display to 768px by 1024px
AppMobi.display.useViewport(768,1024);
//hide splash screen
AppMobi.device.hideSplashScreen();
};
document.addEventListener("appMobi.device.ready",onDeviceReady,false);
function echo(){
alert("clicked");
}
</script>
Thanks a lot
It seems like its not appmobi issue.
I think appmobi lab app for iphone uses safari mobile to run the html5 tests.
So its a safari mobile affair.
It seems play() work when launched by an onclick event. See http://groups.google.com/group/iphonewebdev/browse_thread/thread/91e31ba7ae25e6d4?hl=en
Need to perform some tests...
I have to try this:
http://www.schillmania.com/projects/soundmanager2/
Supporting HTML5 audio can be tedious in modern browsers, let alone
legacy ones. With real-world visitors using browsers ranging from
mobile Safari to IE 6 across a wide range of devices, there can be
many support cases to consider.
SoundManager 2 gives you a single, powerful API that supports both new
and old, using HTML5 audio where supported and optional Flash-based
fallback where needed. Ideally when using SoundManager 2, audio "just
works."
I'm trying to add music to a virtual tour application I'm writing in JS and jQuery and so far my code, shown below, works great in Chrome, FF, IE9, and Opera. But in Safari 5.1.7, which is the newest you can get for a Windows machine, it just doesn't work... Through my research of the problem, I know that Safari doesn't autoplay music and it has to be started manually, but when I click the play button, nothing happens. And, btw, the code inspector in Safari shows that my audio tag is there with the music sources so I don't think it has anything to do with the DOM. Any ideas on my problem?
HTML:
<div id="musicBtns">
<p>Music:</p>
<p id="musicPlayBtn">Play</p>
<p>/</p>
<p id="musicPauseBtn">Pause</p>
</div>
My music object in JS:
var Music =
{
musicBtns: $('#musicBtns'),
playBtn: $('#musicPlayBtn'),
pauseBtn: $('#musicPauseBtn'),
isPlaying: false,
init: function()
{
if(!music.includeMusic) // If the client didn't want any music in the tour app, remove the music btns from the DOM
{
this.musicBtns.remove();
}
else // Else, setup the audio element
{
var parent = this;
var audio = $('<audio loop="true">');
if(music.autoplay)
{
audio.attr('autoplay', 'autoplay');
this.isPlaying = true;
this.togglePlayPause();
}
// Add a source elements and appends them to the audio element
this.addSource(audio, music.ogg); // 'music.ogg' is a reference to the path in a JSON file
this.addSource(audio, music.mp3);
this.musicBtns.append(audio);
// Add event listeners for the play/pause btns
this.playBtn.click(function()
{
audio.trigger('play');
parent.isPlaying = true;
parent.togglePlayPause();
});
this.pauseBtn.click(function()
{
audio.trigger('pause');
parent.isPlaying = false;
parent.togglePlayPause();
});
}
},
addSource: function(el, path)
{
el.append($('<source>').attr('src', path));
},
// Add or remove classes depending on the state of play/pause
togglePlayPause: function()
{
if(this.isPlaying)
{
this.playBtn.addClass('underline');
this.pauseBtn.removeClass('underline');
}
else
{
this.playBtn.removeClass('underline');
this.pauseBtn.addClass('underline');
}
}
}
Edit: Could this be a bug in Safari?
So the problem turned out to be with QuickTime. I guess I must of deleted it off of my machine awhile back because I didn't think I needed it. After I re-installed QuickTime, Safari plays music using the audio tag with no problem. Autoplay even works too.
Kinda funny how the champion of native HTML5 audio/video support, doesn't support HTML5 audio/video without a plugin...
In HTML5 video on Safari I had an issue with this where I had to "load" (which, I think, either starts the buffer or loads the whole thing) before I set it to play. This seemed to actually make things work in a few webkit browsers. So something like:
var a = new Audio("file.mp3");
a.load();
a.play();
Worth a try
When a certain event occurs, I want my website to play a short notification sound to the user.
The sound should not auto-start (instantly) when the website is opened.
Instead, it should be played on demand via JavaScript (when that certain event occurs).
It is important that this also works on older browsers (IE6 and such).
So, basically there are two questions:
What codec should I use?
What's best practice to embed the audio file? (<embed> vs. <object> vs. Flash vs. <audio>)
2021 solution
function playSound(url) {
const audio = new Audio(url);
audio.play();
}
<button onclick="playSound('https://your-file.mp3');">Play</button>
Browser support
Edge 12+, Firefox 20+, Internet Explorer 9+, Opera 15+, Safari 4+, Chrome
Codecs Support
Just use MP3
Old solution
(for legacy browsers)
function playSound(filename){
var mp3Source = '<source src="' + filename + '.mp3" type="audio/mpeg">';
var oggSource = '<source src="' + filename + '.ogg" type="audio/ogg">';
var embedSource = '<embed hidden="true" autostart="true" loop="false" src="' + filename +'.mp3">';
document.getElementById("sound").innerHTML='<audio autoplay="autoplay">' + mp3Source + oggSource + embedSource + '</audio>';
}
<button onclick="playSound('bing');">Play</button>
<div id="sound"></div>
Browser support
<audio> (Modern browsers)
<embed> (Fallback)
Codes used
MP3 for Chrome, Safari and Internet Explorer.
OGG for Firefox and Opera.
As of 2016, the following will suffice (you don't even need to embed):
let src = 'https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3';
let audio = new Audio(src);
audio.play();
See more here.
One more plugin, to play notification sounds on websites: Ion.Sound
Basic Demo
Advanced Demo
Ion.Sound GitHub Page
Advantages:
JavaScript-plugin for playing sounds based on Web Audio API with fallback to HTML5 Audio.
Plugin is working on most popular desktop and mobile browsers and can be used everywhere, from common web sites to browser games.
Audio-sprites support included.
No dependecies (jQuery not required).
25 free sounds included.
Set up plugin:
// set up config
ion.sound({
sounds: [
{
name: "my_cool_sound"
},
{
name: "notify_sound",
volume: 0.2
},
{
name: "alert_sound",
volume: 0.3,
preload: false
}
],
volume: 0.5,
path: "sounds/",
preload: true
});
// And play sound!
ion.sound.play("my_cool_sound");
How about the yahoo's media player
Just embed yahoo's library
<script type="text/javascript" src="http://mediaplayer.yahoo.com/js"></script>
And use it like
<a id="beep" href="song.mp3">Play Song</a>
To autostart
$(function() { $("#beep").click(); });
Play cross browser compatible notifications
As adviced by #Tim Tisdall from this post , Check Howler.js Plugin.
Browsers like chrome disables javascript execution when minimized or inactive for performance improvements. But This plays notification sounds even if browser is inactive or minimized by the user.
var sound =new Howl({
src: ['../sounds/rings.mp3','../sounds/rings.wav','../sounds/rings.ogg',
'../sounds/rings.aiff'],
autoplay: true,
loop: true
});
sound.play();
Hope helps someone.
if you want calling event on the code The best way to do that is to create trigger because the browser will not respond if the user is not on the page
<button type="button" style="display:none" id="playSoundBtn" onclick="playSound();"></button>
now you can trigger your button when you want to play sound
$('#playSoundBtn').trigger('click');
if you want to automate the process via JS:
Include somewhere in the html:
<button onclick="playSound();" id="soundBtn">Play</button>
and hide it via js :
<script type="text/javascript">
document.getElementById('soundBtn').style.visibility='hidden';
function performSound(){
var soundButton = document.getElementById("soundBtn");
soundButton.click();
}
function playSound() {
const audio = new Audio("alarm.mp3");
audio.play();
}
</script>
if you want to play the sound just call performSound() somewhere!
Use the audio.js which is a polyfill for the <audio> tag with fallback to flash.
In general, look at https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills for polyfills to the HTML 5 APIs.. (it includes more <audio> polyfills)
var audio = new Audio('audio_file.mp3');
function post()
{
var tval=document.getElementById("mess").value;
var inhtml=document.getElementById("chat_div");
inhtml.innerHTML=inhtml.innerHTML+"<p class='me'>Me:-"+tval+"</p>";
inhtml.innerHTML=inhtml.innerHTML+"<p class='demo'>Demo:-Hi! how are you</p>";
audio.play();
}
this code is from talkerscode For complete tutorial visit http://talkerscode.com/webtricks/play-sound-on-notification-using-javascript-and-php.php
I wrote a clean functional method of playing sounds:
sounds = {
test : new Audio('/assets/sounds/test.mp3')
};
sound_volume = 0.1;
function playSound(sound) {
sounds[sound].volume = sound_volume;
sounds[sound].play();
}
function stopSound(sound) {
sounds[sound].pause();
}
function setVolume(sound, volume) {
sounds[sound].volume = volume;
sound_volume = volume;
}
We can just use Audio and an object together like:
var audio = {};
audio['ubuntu'] = new Audio();
audio['ubuntu'].src="start.ogg";
audio['ubuntu'].play();
and even adding addEventListener for play and ended