On a .js page in a Visual Studio express ASP.NET solution
why does
window.onload() {
document.getElementById('ambience').play();
}
work(and it does!), but why does
window.onload() {
document.getElementById('ambience').play();
document.getElementById('ambience').stop();
}
NOT stop the music? .pause(); doesn't pause the music either
I also tried:
It does play the music. And I have tried:
window.onload = function() {
var snd = document.getElementById('ambience').play();
var clickmeButton = document.getElementById('playJackpot');
clickmeButton.onclick = playSound;
}
function playSound() {
document.getElementById('ambience').stop();
}
what is the equivalent of .stop() or .pause() if those are not applicable? what set of commands
should I be working with in visual studio in order to get sound to play based on a conditional and then definitively shut off or stop after it has played once, and only once ? The background to this is that I have the play button in a timer control, so that it can operate other features, but each timer tick (and that needs to be set at a fraction of a second) kicks off the play again, so that the sound comes out staccato, because it is starting with every 'tick' of the timer. So, I need to play it, then immediately shut off the sound's ability to play, that is until somebody hits the play button again.
Related
I'm working on a kind of stopwatch/alarm, that's supposed to be running on a website using a modified wordpress plugin. It's function will later be, to start the stopwatch, and once it reaches 15 minutes, there will be an alarm sound. If the watch then doesn't get reset within the next 3 minutes, there will be another action (notification or something, not important right now, that part I already figured out), and if it's reset, it starts the whole thing again (will run for multiple hours).
I've set up the infrastructure via wordpress, and now my only problem is the stopwatch itself.
My problem right now is, that it "kind of" stops running, whenever someone moves to another tab or program. With "kind of", I mean: If the alarm sound was played ONCE, and I then reset it, it keeps counting even when switching tab after that. But on the first page refresh, it doesn't; except sometimes it does, but very slowly (1 "second" takes 3 real seconds). This is what my code looks like right now:
var silence = new Audio('exampleSilence.mp3'); //Audio-file with no content (so just silence)
var audio = new Audio('exampleAlarm.mp3'); //Audio-file with random song/alarm sound
var time=0;
var running=0;
function strtpause () { //Function responsible for start/pause button
if(running==0){
running=1;
increment();
document.getElementById("strtpause").innerHTML="Pause"
}
else{
running=0;
document.getElementById("strtpause").innerHTML="Resume"
return;
}
}
function reset(){ //Function responsible for resetting the stopwatch timer. At first also stopped
//the counting, but I disabled that part as I want it to keep going
//running=0;
time=0; //Sets time back to 0, so timer can start from 0 again
//document.getElementById("strtpause").innerHTML="Start"
document.getElementById("output").innerHTML="00:00"
audio.pause(); //Will also stop the alarm
audio.currentTime = 0; //And set the alarm time back to 0
}
function increment(){ //The actual stopwatch timer function
if(running==1){
setTimeout(function(){
time++;
var mins=Math.floor(time/60);
var secs=Math.floor((time)-(mins*60));
if(mins<10){
mins="0"+mins;
}
if(secs<10){
secs="0"+secs;
}
document.getElementById("output").innerHTML=mins+":"+secs;
if(1<time<9){ //I attempted to play a silent audio file in the background
silence.play(); //to keep the process running, but didn't have an effect
}
if(1<time<9){ //Also tried playing the audio file but very very silent.
audio.volume = 0.001; //It did work, but made timer go slower than regular seconds
audio.play();
}
if (time>10){ //Once the timer reaches a certain time, the alarm is played
audio.volume = 0.5; //Adjusts sound volume
audio.play();
}
increment();
},1000);
}
}
My solution ideas until now were:
-Change the setTimeout increments -> No effect, except with smaller increments it seemed to go slower
-Let it play a "silent" audio file with no actual sound content, so it "has something to do" (no idea if that makes sense, but audio files keep playing in background)
-Let it play an audio file with content while waiting, but very quietly (volume = 0.001). Did work, but made the stopwatch go way too slow, with 1 "second" = 3 actual seconds.
Ideas on how to keep the code running on any OS/Browser are appreciated! I'd prefer not to write/setup a different file or language, as my webdevelopment skills are very very basic, and I don't have rights to edit everything on the website.
Time delay for setTimeout() / setInterval() methods executing on inactive browser tabs are set to one second regardless of their value defined in code.
More about that here: https://usefulangle.com/post/280/settimeout-setinterval-on-inactive-tab
I need a sound on a mouse over event, I have this way but its problem comes from a delay between the mouse over and the sound playing, which is due (I supposed) the embed sound deal on the code. I would like to know if there is a better way using js/jquery). But not the new html5 audio tag which I don't want to implement in this particular case.
An ajax call loads the file, then I attached to the mouseOver a function named playSound()
function playSound()
{
$setSound = document.getElementById("soundWrapper").innerHTML="<embed id='sound' src='href' type=audio/mpeg hidden=false autostart=true volume=12>";
}
Then to the mouseOut event a function named stopSound()
function stopSound()
{
$stopSound = document.getElementById("soundWrapper").innerHTML="";
}
Nothing fancy but it does work. The problem as a said is the delay to playing the sound. Is there a way to play/stop the already embedded sound, not just embed a new one every time, or something alike?.
Thanks for your time and help.
Greetings.
If you have your AJAX load an audio tag (http://www.w3schools.com/tags/tag_audio.asp) into the desired place, you can play it using the .play() method in JS. Then it becomes really easy
$(YOURMOUSEOVERELEMENT).on('mouseover', function(){$('#sound').play()});
Then if you want to stop the audio when the mouse leaves:
$(YOURMOUSEOVERELEMENT).on('mouseout', function(){$('#sound').stop()});
Is there a way to use the Youtube API to play a video until a certain point in the video and then pause it?
I've modified the code from the YouTube Player API Reference for iframe Embeds to pause play after a certain number of seconds.
Demo
The code works by waiting for the onPlayerStateChange event. When the event fires, it checks the event to see if it's a PLAYING event. If it is, it calculates the remaining time from the current time (getCurrentTime() method) to the desired pause point (hardcoded as the stopPlayAt variable). It sets a Javascript timer to wait that difference and then pass the API a command to pause the video.
You can use the command cueVideoById in Object syntax to achieve this.
See here: https://developers.google.com/youtube/iframe_api_reference#cueVideoById
This is the way it should look like to start a video like this.
//Minimal Example
player.cueVideoById({videoId:String, endSeconds:Number});
player.playVideo();
EDIT: The above sample stops the video. If you want to pause it, a little more action is required by the JavaScript code.
In detail, you have to poll for the right time.
function checkTime() {
if ( player.getCurrentTime() == finishTime )
player.pauseVideo()
else
setInterval(checkTime, 500);
}
checkTime();
Or keep track of the time in JS:
var duration = finishTime - player.getCurrentTime();
player.playVideo()
setInterval("player.pauseVideo();", duration*1000);
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);
}
I currently have an HTML5 video event issue in Safari. I am playing a single video on my page. The video loads and plays correctly. However, the play event does not always fire. If the user:
Clicks play
Watches the video to the end (ended event fires)
Clicks play again
The play event does not fire on the second click. If I pause/play the movie at that time, the correct events fire.
How can I make the video tag's play event fire if the video has completed and the user presses play again?
drawVidPlayer is called with the videos index as part of the page render
function drawVidPlayer(vindex){
var turl=vidList[vindex]['thumbUrl'];
var vurl=vidList[vindex]['url'];
var valias=vidList[vindex]['type'];
destroyVidPlayer();
$('#mediaspot').css('backgroundColor', '#000000');
$('#mediaspot').show();
$('#mediaspot').html('<video controls="controls" id="twnvideo" poster="'+turl+'" style="height:225px; width:460px;"><source src="'+vurl+'" type="video/ogg" /><source src="'+vurl+'" type="video/mp4" /><source src="'+vurl+'" type="video/webm" />Your browser does not support the video tag.</video>').appendTo('#wrap_media_vod');
var velem=document.getElementsByTagName('video')[0];
velem.addEventListener('play', initVidTimer, false);
velem.addEventListener('pause', killVidTimer, false);
velem.addEventListener('ended', killVidTimer, false);
}
function destroyVidPlayer(){
var velem=document.getElementsByTagName('video')[0];
if(velem!=undefined){
velem.removeEventListener('play', initVidTimer);
velem.removeEventListener('pause', killVidTimer);
velem.removeEventListener('ended', killVidTimer);
}
$('#mediaspot').empty();
$('#mediaspot').html('');
}
function initVidTimer(){
if(activityTimer==null){
external.OnUserActivity(19);
activityTimer=setInterval(function(){
external.WriteLog('activity timer running');
external.OnUserActivity(19);
}, 5000);
}
}
function killVidTimer(){
clearInterval(activityTimer);
activityTimer=null; // Kill keepAlive timer
var velem=document.getElementsByTagName('video')[0];
external.WriteLog(velem.ended);
}
HTML5 now specifies that the browser must throw the timeupdate, paused, and ended events when the playback position reaches the end of a media file, but the spec wasn't always that clear. As a result, this behavior is inconsistent between browsers. Some don't set paused=true or fire the paused event when the file ends.
In your Safari issue, paused is still equal to false when the video starts to play for the second time - so there is no reason for the browser to fire the play event again.
This may no longer be an issue in Safari 6, but it still breaks in IE 9. Take a look at the End Events column in this chart from longtailvideo.com - they outline the inconsistencies well.
It would easy to normalize this issue with a couple lines of code - like this:
$("video").on("ended", function () {
if (!this.paused) this.pause();
});
This puts the video in the paused state on ended, so it will throw the play event correctly on replay.
You can try this working sample in IE 9 or to see what I mean on this jsfiddle: http://jsfiddle.net/PWnUb/
I had the same issue, I solved with a bit of jquery:
function videoend(){
var duration = $("video").get(0).duration;
var current = $("video").get(0).currentTime;
if(current==duration){
//Whatever you wanna do when video ends
};
}
$(document).ready(function(){
setInterval("videoend()", 200); //or any other time you wanna use
});
Hope this helps.