Is it possibly in Jquery or Javascript, without the use of libraries to record audio for X seconds and save to a audio file. I've looked at getUserMedia, an I see that it can retrieve audio and video from the webcam. I am currently using the webcam with another library: Clmtracker and for that reason I would want to try and do this without any more external libraries.
I want to store the recorded audio in a div. I am currently taking a picture and assigning it a unique name, so I am wondering how I can capture a short section of audio and store it in the same generated div.
Question: How can I achieve getting audio for 5 seconds from webcam?
Sub-Question: How can I store that in an element within a div?
My Code for capturing Img and Data on my page
function capturePage() {
var now = new Date();
if (nextAllowedCapture <= now) {
// Do capture logic
audioElement.play();
counting++
console.log("Capturing...");
$(".capturing").show().delay(500).fadeOut(3000);
var innerDiv = document.createElement('div'),
innerDivImg = document.createElement('canvas'),
image = document.createElement('img'),
ul = document.createElement('ul');
innerDiv.className = 'divCreate';
innerDiv.id = 'img' + counting;
innerDivImg.height = 450;
innerDivImg.width = 600;
innerDivImg.getContext('2d').drawImage(vid, 0, 0);
image.id = 'image' + counting;
image.src = innerDivImg.toDataURL();
image.className = 'divCreateImg';
innerDiv.appendChild(image);
innerDiv.appendChild(ul);
document.getElementById('galleryWrapper').appendChild(innerDiv);
$('#measurements h4').each(function () {
$("#" + innerDiv.id + " " + 'ul').append('<li>' + $(this).text() + ': ' + $(this).next().text());
});
nextAllowedCapture = new Date();
nextAllowedCapture.setSeconds(nextAllowedCapture.getSeconds() + coolDownSeconds);
} else {
nextCapTime = (nextAllowedCapture.getTime() - now.getTime()) / 1000;
console.log("Can't capture again yet. This function can be executed again in " +
(nextAllowedCapture.getTime() - now.getTime()) / 1000 +
" seconds.");
}
}
You can see the code for Recorder.js as an example which implements the capture audio functionality and saves it in wav format using getUserMedia annd yes, just html5 and javascript.
Now you might say that you asked without any plugins. In fact, I checked the code for recorder.js which is just 90 lines of plain javascript, just html5 and javascript.
UPDATE: I found one online demo which experiments with this and it seems to work fine and all source code is open. You might want to check that out.
Here is the link:
Recorder JS
Here is another link to tweak it and make it more functional.
Recording MP3 Using Only HTML5 and JavaScript
Related
So this is the small issue I am having. I am trying to send an object from illustrator to photoshop, but I want to copy and past 2 versions one that is stroked and one that is stroked. The main problem I have is the paste in photoshop comes after I have done the 2 different versions. the P is the path item that is the outline. so it will paste two versions that have no stroke because it runs the first past after the second copy has already run.
function CreateLabel(Label)
{
var P = Label.pageItems[0]
app.copy()
// get Print Area Width and Height and convert to inces at 300 DPI
var LW = "\"" + String(Math.floor((Label.width/72)*300)) + "px\""
var LH = "\"" + String(Math.floor((Label.height/72)*300)) + "px\""
// create the new document
var Cmd = "app.documents.add(" + LW + "," + LH + ", 300,\"Label\", NewDocumentMode.RGB,DocumentFill.TRANSPARENT);";
TellPhoto(Cmd)
app.copy()
TellPhoto('app.activeDocument.paste();')
P.stroked = false
app.copy()
TellPhoto('app.activeDocument.layers.getByName(\"Layer 1\").remove();' )
//bt.body = 'BridgeTalk.bringToFront("illustrator");';
//bt.send(5)
};
// paste the saved bit
function TellPhoto(Message)
{
var bt = new BridgeTalk();
bt.target = "photoshop";
bt.body = Message
bt.onError = function(e)
{
alert(e.body);
};
bt.send(1);
}
so I need something that will almost pause until photoshop has pasted the current clipboard in.
I come across similar glitches from time to time with app.copy() and app.paste() commands. Quite often an additional pause ($.sleep(200)) before app.paste() helps. My guess is the app (Illustrator) just can't keep up to copy all the data by the time when another app (Bridge or even the same Illustrator) tries to paste it.
I'm building a CMS site for a client who'll be uploading videos. I'm trying to build a custom progress bar for each video too, I've done this before but there was only one video present so I could use a getElementByID to call each video, but as there's going to be multiple videos per page I tried to call an each function and find each element by it's class within it's parent container.
You can see my codepen here: https://codepen.io/neal_fletcher/pen/JJzbYP
As you can see though the progress bar isn't moving when the video plays (as it should), there's only one video here but there will be multiple videos so I CANT use a function that relies on ID's of each element.
My jQuery markup below too:
window.onload = function() {
$(".video-wrap").each(function() {
var slideshowVideo = document.getElementsByClassName("homepage-video");
var slideshowSeek = document.getElementsByClassName("seek-bar");
slideshowSeek.addEventListener("change", function() {
// Calculate the new time
var time = slideshowVideo.duration * (slideshowSeek.value / 100);
// Update the video time
slideshowVideo.currentTime = time;
});
});
Any suggestions on the best solution for this would be greatly appreciated!
Working code
window.onload = function() {
$(".video-wrap").each(function() {
var slideshowVideo = document.getElementsByClassName("homepage-video");
var slideshowSeek = document.getElementsByClassName("seek-bar");
slideshowSeek[0].addEventListener("change", function() {
// Calculate the new time
var time = slideshowVideo.video.duration * (slideshowSeek[0].value / 100);
// Update the video time
slideshowVideo.video.currentTime = time;
});
slideshowVideo.video.addEventListener('timeupdate', function(video){
slideshowSeek[0].value = slideshowVideo.video.currentTime * 100 / slideshowVideo.video.duration;
}, false);
});
}
check below pen
https://codepen.io/anon/pen/qjvRXP?editors=0110
This is what I'm working with:
var numberOfSongs = 5
var sound = new Array(numberOfSongs+1)
sound[0]= "https://domain.com/media/audio1.mp3"
sound[1]= "https://domain.com/media/audio2.mp3"
sound[2]= "https://domain.com/media/audio3.mp3"
sound[3]= "https://domain.com/media/audio4.mp3"
sound[4]= "https://domain.com/media/audio5.mp3"
function randomNumber(){
var randomLooper = -1
while (randomLooper < 0 || randomLooper > numberOfSongs || isNaN(randomLooper)){ randomLooper = parseInt(Math.random()*(numberOfSongs+1))
}
return randomLooper
}
var randomsub = randomNumber()
var soundFile = sound[randomsub]
document.write ('<EMBED src= "' + soundFile + '" hidden=true autostart=true loop=true>')
A friend gave me this for my website. This is used to play a randomly selected mp3 file from a list of 5 of them. I'm trying to add volume values to this (Nothing that will visibly show as controls) but to be put in as JS.
I want to be able to upload audio but not have to edit the audio itself in a audio editor, I'd rather do it here in JS for my convenience. What would be a good way to add volume values to this?
Eg: volume at default is set at 25% but can't be changed unless you edit the source of this JS. There should be no controls visible.
I'm not good at JS at all. I've looked up how to build something like that into this but I don't know where to begin.
Use Audio
var audio = new Audio(soundFile);
audio.loop = true;
audio.autoplay = true;
// set volume here, between 0 and 1
audio.volume = .7;
I'm creating a 'catch falling items' game, and have successfully drawn the 'catcher' image and the 'falling items' images onto the canvas. But I'd like to also show an image (x.png) when a falling image is not caught and hits the base of my html5 canvas. The generateX function is called from the animate function and when a falling image hits the base of the canvas. The sound.play() is working. The console.logs in the generateX function log the following - 2,3 | 1,3 | 1,3 - so I know that the image is not completely loaded the first time this function runs. Everything seems to be working EXCEPT for the actual image displaying. I tried to structure it in ways that other threads have suggested, but nothing is working. Any help is much appreciated!
generateX: function() {
console.log('inside generateX func');
var imgX = new Image();
imgX.src = 'assets/x.png';
function drawX() {
console.log(3);
counter+=20;
context.drawImage(imgX, xIcon.x + counter, xIcon.y, xIcon.width, xIcon.height);
xArr.push(imgX);
console.log('xArr', xArr);
}
if (imgX.complete) {
console.log(1);
drawX();
} else {
console.log(2);
imgX.onload = drawX;
}
helper.checkMisses();
}
animate: function() {
var sound;
if (continueAnimating) {
requestAnimationFrame(helper.animate);
}
for (var i = 0; i < surveys.length; i++) {
var survey = surveys[i];
if (helper.isColliding(survey, dinoSaurus)) {
sound = new Audio("audio/coinSound.mp3");
sound.play();
score += 5;
helper.resetSurvey(survey);
}
survey.y += survey.speed;
// if the survey is below the canvas,
if (survey.y > canvas.height) {
sound = new Audio("audio/buzzerSound.mp3");
sound.play();
helper.generateX();
helper.resetSurvey(survey);
}
}
// redraw everything
helper.drawAll();
}
--
resetSurvey: function(survey) {
// randomly position survey near the top of canvas
survey.x = Math.random() * (canvas.width - surveyWidth);
survey.y = 40 + Math.random() * 30;
survey.speed = (0.55 + Math.random()) * 0.9;
}
Try loading your image earlier
If I understand your situation correctly, I think the issue is that you need to load the image earlier so that it is easily ready by the time you want to draw it, rather than waiting to load it only inside generateX. The way you are currently coding it, you are loading the image (imgX.src = ...) and then immediately trying to draw it. True, you are checking if the loading is complete and, if not, trying again shortly after. However, a better strategy is to load the image much earlier, e.g. during game initialization.
Demo
The code snippet below demonstrates the difference that this makes. It loads 2 different images. The only difference between the two is that one (on the left) is loaded ahead of time and the other (on the right) is only loaded inside generateX. The former image displays properly the 1st time through the game cycle while the latter image is missing the 1st time and only displays properly the 2nd time through.
function loadLeftImageWellBeforeRunningGenerateX() { // correct timing
imgs[0] = new Image();
imgs[0].src = 'http://placehold.it/200x100.png';
}
function loadRightImageInsideGenerateX() { // incorrect timing
imgs[1] = new Image();
imgs[1].src = 'http://placehold.it/100x50.png';
}
function generateX() {
loadRightImageInsideGenerateX();
log('--inside generateX func');
imgs.forEach(function(imgX, num) { // same as your original code, just done for 2 different images
if (imgX.complete) {
log("----image #" + num + " (" + side[num] + "); " + 1 + ", i.e. image complete");
drawX(imgX, num);
} else {
log("----image #" + num + " (" + side[num] + "); " + 2 + ", i.e. image not complete");
imgX.onload = drawX(imgX, num);
}
});
}
function drawX(imgX, num) { // same as your original code, just allows placement of 2 images side-by-side
log("----image #" + num + " (" + side[num] + "); " + 3 + ", i.e. drawing image (" + prefix[num] + "successfully)");
context.drawImage(imgX, num * 150 + 10, 10, 100, 50);
if (num === 1) {prefix[1] = "";}
}
var
imgs = [],
numClicks = 0,
side = ["left", "right"],
prefix = ["", "un"],
button = document.querySelector("button"),
canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d');
context.fillStyle = "yellow";
context.fillRect(0, 0, 300, 150);
// as far as game logic goes, the only important lines below are marked with arrows
// the rest is just "fluff" to make the demo more understandable to the user
button.addEventListener("click", function() {
numClicks += 1;
if (numClicks === 1) {
log("You must clear your browser's recent cache every time you run this snippet " +
"in order for it to demonstrate the problems and solutions " +
"associated with loading images in this code.");
button.innerHTML = "Clear browser cache and click here again to start game initialization";
} else if (numClicks === 2) {
loadLeftImageWellBeforeRunningGenerateX(); // <----- ***
log("Game initializes. No images should yet be visible, " +
"but image #0 (left) should be loading/loaded now, i.e. ahead of time. " +
"Image #1 (right) is not yet loading/loaded. Click again to 'play game'.");
button.innerHTML = "Do NOT clear the browser cache and click here again to start playing game";
} else {
button.innerHTML = "Do NOT clear the browser cache and click here again to continue playing game";
if (numClicks === 3) {
log("Game begins. Images are required for the first time. Only the pre-loaded left image shows " +
"even though loading both is attempted.");
} else {
log("Game continues. On second and subsequent re-draws, both images are now available and visible.");
}
generateX(); // <----- ***
}
});
function log(msg) {
document.body.appendChild(document.createElement("p")).innerHTML = msg;
}
p {
margin: 0.2em;
}
<canvas id="myCanvas" width="300" height="80"></canvas>
<div>
<button>Click here to begin demo</button>
</div>
Your browser's cache can hide this bug
By the way, if and when you try to debug this kind of thing, be aware that many/most/all browsers cache images, making it potentially difficult to replicate this kind of bug if you're not aware of what's going on. For example, you might run your buggy code and the image is missing the first time through the game cycle. You study your code, make a change to try to fix the bug and run the code a second time. Voila, it looks like the problem is fixed because the image now appears the first time through the game cycle. However, it may, in fact, only be showing up in that first cycle not because the bug is fixed but because the browser is able to use the cached image even in the first game cycle, eliminating the need to load it from its source. In short, if you're trying to debug an issue like this where you suspect the timing of file loading is important but the bug only appears sometimes, try clearing your browser's recent cache to see if that makes the bug more apparent.
To clear a browser's cache:
Firefox (for Mac or Windows, v44...): click "History" / click "Clear Recent History..." / click to open "Details" if necessary / check "Cache" / click "Clear now"
Chrome (for Mac, v48...) "Chrome" (left menu item) / "Clear Browsing Data..." / select "Cached images and files" / click "Clear browsing data"
Chrome (for Windows, v48...) click customize-and-control icon (at the right) / click "More tools..." / click "Clear browsing data..." / click "Clear browsing data"
Internet Explorer (for Windows, v11...) click "Tools" / click "Delete browsing history" / select "Download history" / click "Delete"
I am trying to calculate the measure time of html 5 video. I use Javascript to listen to html5 video event loadstart and canplaythrough using:
media.addEventListener('loadstart'getStartTime(){
startTime = new Date().getTime();},
false)
and similar for endTime with event set as canplaythrough to listen.
However I could not get any data.
Can someone please guide me how to measure video load time using Javascript.
Thank you for your response, but the solution is I believe using jQuery; however, I was wondering if it is possible from Javascript. I have attached a copy of my code:
function loadVideo(){
var timeNow = Date.now(), timeStartLoad, timeFinishLoad;
myVideos = new Array();
myVideos[0] = "trailer.mp4";
myVideos[1] = "trailer.ogg";
myVideos[2] = "trailer.m4v";
var videoId = document.getElementById('idForVideo');
var video = document.createElement('video');
for(var i=0; i<myVideos.length; i++){
var source = document.createElement('source');
source.setAttribute('src', myVideos[i]);
video.appendChild(source);
}
video.load();
video.addEventListener('loadstart', function(){
timeStartLoad = Date.now() - timeNow;
}, false);
video.addEventListener('hasenoughdata', function(){
timeFinishLoad = Date.now() - timeStartLoad;
}, false);
idForVideo.appendChild(video);
newDiv = document.getElementById('newDiv');
newDiv.innerHTML = "BodyLoad: " + timeNow + " " + "; Video Load: " + timeStartLoad + "; Video Loaded: " + timeFinishLoad;
//alert(timeStartLoad);
}
However I get undefined for both timestartLoad and timeFinishLoad. My html body has onload method linked to this function.
Your code has some (copy & paste) syntax problems.
var timeInit = Date.now(), timeLoad, timeCanPlay;
$("movie").addEventListener('loadstart', function(){
timeLoad = Date.now();
$("t1").innerHTML = "load: " + (timeLoad - timeInit) + " msecs";
});
$("movie").addEventListener('canplaythrough', function(){
timeCanPlay = Date.now();
$("t2").innerHTML = "canplay: " + (timeCanPlay - timeLoad) + " msecs";
});
$("movie").src = "http://ia600208.us.archive.org/12/items/FarSpeak1935/FarSpeak1935_512kb.mp4";
$("movie").play();
Try out: http://jsfiddle.net/noiv/98xZP/:
Hey, I figured it out.
The reason seems to be due to the fast responsiveness of the browser that it fetches the data before even the event is catched. A solution as provided by opera seems to work. Include the event listener at the inline script and make addEventListener for window object.
More details at:
http://dev.opera.com/articles/view/consistent-event-firing-with-html5-video/
While I can't comment, I have added a fork to the fiddle posted above by #noiv , as the fiddle had some JS errors. Thanks #noiv for putting me on the right direction.
http://jsfiddle.net/truedat101/Gbfj2/7/
$("movie").addEventListener('loadstart', function(){
timeLoad = Date.now();
console.log("loadstart event time: " + timeLoad + ", delta: " + (timeLoad - timeInit));
// alert("loadstart event time: " + timeLoad + ", delta: " + (timeLoad - timeInit));
});
It is worth noting the whatwg is attempting to get some uniformity around video metrics in the browser, so that there will be some common attributes supported by the browser, though it appears already that this work will be split across party lines, with Mozilla supporting their own metrics, Chromium team supporting theirs, and Apple Safari supporting theirs.