I declare a audio file in my page:
var audio = new Audio('my.mp3');
then I use click event to play it:
$(document).click(function () {
audio.currentTime = 0; // to make sure it play from the begain
audio.play();
})
It can play only at the first click time, after it ended, I click the document, it can not play again.How can I let it play again?
I tested this in Chrome and an exception occurs due to the audio.currentTime statement.
This worked (also in IE9):
$(document).click(function () {
audio.src = "my.mp3";
audio.play();
})
Related
I am trying to use Chrome's screen sharing feature to make a screen recorder and save the video in MP4 format. However, I have no idea how I do this. The demo is at https://figgycity50.kd.io/screencap.html (include https!) and the code is:
<video autoplay></video>
<button>start</button>
<script>
navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.getUserMedia;
var stream = null;
button = document.querySelector("button");
function start(e) {
// Seems to only work over SSL.
navigator.getUserMedia({
video: {
mandatory: {
chromeMediaSource: 'screen',
maxWidth: 1280,
maxHeight: 720
}
}
}, function(s) {
stream = s;
button.textContent = 'Stop';
button.removeEventListener('click', start);
button.addEventListener('click', stop);
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(stream);
video.autoplay = true;
stream.onended = function(e) {
//The save code should go here.
};
//document.body.appendChild(video);
}, function(e) {
});
}
function stop() {
stream.stop();
button.addEventListener('click', start);
button.textContent = 'Capture your screen';
}
button.addEventListener('click', start);
</script>
How do I do this?
You cannot save directly to MP4 format with the way the current state of getUserMedia API is working, you can however save in webm format and convert it afterwards.
Several attempts have been made, webRTC experiment project has several versions of recording in the browser implemented:
https://www.webrtc-experiment.com/RecordRTC/
You can however save directly in MP4 format using HTML Media Capture.
This works by extending the <input type="file"/> and adding new values for the accept parameter with options for audio, video and photo/snapshot. This however works only for mobile browsers, as the desktop browser will only interpret it as a simple file upload.
HDFVR has a demo of this, if you access their demo from a mobile device.
More details can be read in the following article:
http://hdfvr.com/html5-video-recording
I'm trying to follow this guide on capturing video from webcam in HTML5
http://www.html5rocks.com/en/tutorials/getusermedia/intro/
I have copied and pasted the following code but Chrome does not ask for permission to use my camera
<video autoplay></video>
<script>
var onFailSoHard = function(e) {
console.log('Reeeejected!', e);
};
// Not showing vendor prefixes.
navigator.getUserMedia({video: true, audio: true}, function(localMediaStream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(localMediaStream);
// Note: onloadedmetadata doesn't fire in Chrome when using it with getUserMedia.
// See crbug.com/110938.
video.onloadedmetadata = function(e) {
// Ready to go. Do some stuff.
};
}, onFailSoHard);
</script>
Whereas when I click "capture video" in the guide it works, my webcam shows...
Another website has similar code but yet again it's not working for me
http://dev.opera.com/articles/view/playing-with-html5-video-and-getusermedia-support/
<!-- HTML code -->
<video id="sourcevid" autoplay>Put your fallback message here.</video>
/* JavaScript code */
window.addEventListener('DOMContentLoaded', function() {
// Assign the <video> element to a variable
var video = document.getElementById('sourcevid');
// Replace the source of the video element with the stream from the camera
if (navigator.getUserMedia) {
navigator.getUserMedia('video', successCallback, errorCallback);
// Below is the latest syntax. Using the old syntax for the time being for backwards compatibility.
// navigator.getUserMedia({video: true}, successCallback, errorCallback);
function successCallback(stream) {
video.src = stream;
}
function errorCallback(error) {
console.error('An error occurred: [CODE ' + error.code + ']');
return;
}
} else {
console.log('Native web camera streaming (getUserMedia) is not supported in this browser.');
return;
}
}, false);
I was wondering if I'm missing something or has something changed, because none of the sample code has worked for me so far.
Found out what was happening. For anyone wondering, on Chrome you only have access to the webcam if running from a server. It won't work on just a file.
I've been absolutely everywhere (I think) and can't seem to find a way to call a stop event in an html5 audio controller. My audio controller has a playlist where each track will play when selected or cycle through each track to the next. There's also a next button which works.
My play/pause button looks like this:
function playPause() {
var audioPlayer = document.getElementsByTagName('audio')[0];
if(audioPlayer!=undefined) {
if (audioPlayer.paused) {
audioPlayer.play();
} else {
audioPlayer.pause();
}
} else {
loadPlayer();
}
}
I need a "Stop" button that stops the audio and goes back to the beginning of the track currently being played. I thought about using the current playback postion somehow, but can't get my head around that.
I've also tried this (adapted by advice here in another question), to no avail:
function stop() {
var audioPlayer = document.getElementsByTagName('audio');
addEventListener('loadedmetadata', function() {
this.currentTime = 0;
}, false);
}
Any ideas?
If your play/pause is working, this should work for stop:
function stop() {
var audioPlayer = document.getElementsByTagName('audio')[0];
audioPlayer.pause();
audioPlayer.currentTime = 0;
}
Here is a small demo code, where you can play, pause and stop an audio.
Live Demo
HTML
<input type="button" value="play" id="playBtn" />
<input type="button" value="pause" id="pauseBtn" />
<input type="button" value="stop" id="stopBtn" />
Jquery
var source = "http://www.giorgiosardo.com/HTML5/audio/audio/sample.mp3"
var audio = document.createElement("audio");
audio.src = source;
$("#playBtn").click(function () {
audio.play();
});
$("#pauseBtn").click(function () {
audio.pause();
});
$("#stopBtn").click(function () {
audio.pause();
audio.currentTime = 0;
});
Source
If you want to stop the music and abort the downloading operation you can use this code:
<button id="btnStop" onclick="player.src = ''; player.src = 'song.mp3';">Stop</button>
We are using java here to change the song src and then put it back there! Tricky but worky
I am working on a project which is in html5. I am testing it in ipad. I have one background audio which play when page load. I made all code to play it, but it not play when it page load. If i click on play button then it play nicely.
Now what i want is to play audio automatically (autoplay). Below is my code,
$(document).ready(function() {
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'S6.mp3');
audioElement.controls = true;
audioElement.load();
audioElement.play();
audioElement.play();
$('.play').live('click',function() {
//alert('play'); // alert('asdsad');
audioElement.play();
$("#play").removeClass("play").addClass("pause");
});
$('.pause').live('click',function() {
// alert('pause'); // alert('4545');
audioElement.pause();
//$("#play").html('<a href="#" title="Play" class="play" id="play">');
$("#play").removeClass("pause").addClass("play");
});
$('.soundhover').live('click',function() {
audioElement.volume=0;
$("#off").removeClass("soundhover").addClass("soundoff");
});
$('.soundoff').live('click',function() {
audioElement.volume=1;
$("#off").removeClass("soundoff").addClass("soundhover");
});
});
autoplay doesn't work on iOS:
https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html#//apple_ref/doc/uid/TP40009523-CH5-SW1
I need to tell, whether video cannot be played ("x" sign is shown in browser).
This code does't works. "onerror" event will never be fired under Firefox
var v = document.getElementsByTagName("video")[0];
if ( v != undefined )
v.onerror = function(e) {
if ( v.networkState == v.NETWORK_NO_SOURCE )
{
// handle error
}
}
What's wrong here ?
"onerror" is not a valid event type for <video>
Use "error" instead.
document.getElementsByTagName('video')[0].addEventListener('error', function(event) { ... }, true);
For a complete list of events for <video> go here: https://developer.mozilla.org/En/Using_audio_and_video_in_Firefox
From Firefox 4 onwards, the 'error' event is dispatched on the <source> element.
And you should add an error handler on the only/last source:
HTML
<video id="vid" controls>
<source src="dynamicsearch.mp4" type="video/mp4"></source>
<source src="otherdynamicsearch.avi" type="video/avi"></source>
</video>
JS
var v = document.querySelector('video#vid');
var sources = v.querySelectorAll('source');
if (sources.length !== 0) {
var lastSource = sources[sources.length-1];
lastSource.addEventListener('error', function() {
alert('uh oh');
});
}
JQuery
$('video source').last().on('error', function() {
alert('uh oh');
});
AngularJS
You can create an error handling directive (or just use ng-error):
<video id="vid" controls>
<source src="dynamicsearch.mp4" type="video/mp4"></source>
<source src="otherdynamicsearch.avi" type="video/avi" ng-error="handleError()"></source>
</video>
Where the error handling directive's link function should do (copied from ng-error):
element.on('error', function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
It's good to know that Chrome and Firefox have different onerror callbacks. The error must therefore be mapped. Mozilla uses error.originalTarget.
Here is a sample on how to do it with pure JavaScript:
const file = 'https://samples.ffmpeg.org/MPEG-4/MPEGSolution_jurassic.mp4';
window.fetch(file, {mode: 'no-cors'})
.then((response) => response.blob())
.then((blob) => {
const url = window.URL.createObjectURL(blob);
const video = document.createElement('video');
video.addEventListener('error', (event) => {
let error = event;
// Chrome v60
if (event.path && event.path[0]) {
error = event.path[0].error;
}
// Firefox v55
if (event.originalTarget) {
error = error.originalTarget.error;
}
// Here comes the error message
alert(`Video error: ${error.message}`);
window.URL.revokeObjectURL(url);
}, true);
video.src = url;
document.body.appendChild(video);
});
The above example maps an incoming error event into a MediaError which can be used to display an error playback message.
To catch error event, you should use video.addEventListener():
var video = document.createElement('video');
var onError = function() { // your handler};
video.addEventListener('error', onError, true);
...
// remove listener eventually
video.removeEventListener('error', onError, true);
Note that the 3rd parameter of addEventListener (on capture) should be set to true. Error event is typically fired from descendants of video element ( tags).
Anyway, relying on video tag to fire an error event is not the best strategy to detect if video has played. This event is not fired on some android and iOS devices.
The most reliable method, I can think of, is to listen to timeupdate and ended events. If video was playing, you'll get at least 3 timeupdate events. In the case of error, ended will be triggered more reliably than error.
Try adding the event listener to the tag instead - I think the onerror attribute ("error" event) works on the source tag now, not the video tag.
Pug example
video(src= encodeURI(item.urlVideo), type='video/mp4' onerror="myFunction('param',this)")
script(src='/javascripts/onerror.js')
function myFunction(param, me) {
console.log(me);
me.poster = './images/placeholder.jpg'; }