Play a loaded file in javascript - javascript

I'm trying to load a file from the user and want to play it with javascript.
The file is loaded correctly, and I can access it seeing the name, the type and so on, with the FileList API.
What I can't do is to play the obtained file. I tried to do
myFile.play();
like I always do with loaded file, but it doesn't work.
Any idea?

If you only want to play the media content, instead of using FileReader, i suggest you to use the createObjectURL method. It is more efficient since it do not create a string containing the file content.
https://developer.mozilla.org/fr/docs/DOM/window.URL.createObjectURL
Just do :
audio/video.src=window.URL.createObjectURL(myFile);
Don"t forget to revoke your uri when loading another media file to avoid memory leaks :
window.URL.revokeObjectURL(audio/video.src);

You need FileReader API too (API compatibility) and your browser need support HTML5 audio tag.
Something like this:
<body>
<input type='file' id='fileInput' />
<audio id='player' />
<script type='javascript'>
var fileInput = document.getElementById("fileInput");
var freader = new FileReader();
freader.onload = function(e) {
document.getElementById('player').src = e.target.result;
document.getElementById('player').play();
}
fileInput.onchange = function(e) {
var files = e.target.files;
freader.readAsDataURL(files[0]);
}
</script>
</body>
You can read here for more.
My answer based on migerh's solution

Related

Displaying and downloading a pdf in an iframe

I am using wix and in order to customize any html you need to use an embed object which creates a sandboxed iframe on the site. I have a decent grasp of how this works and posting messages to it but what I am having difficulties with is generating a pdf into this iframe.
I have done some reading and I think I get the overall concept. While traditionally you would just set the source to some document on a server somewhere I am generating the content dynamically based on user action. So it looks like something like pdfkit and creating a blob is the way to go.
I think I am able to generate the pdf without issues as well as a blob url no problem
[![console image][1]][1]
I can manually open the console and get that URL and paste it in the browser and the document opens exactly how I expect it. However I can't get it to display normally in the browser.
I have tried setting the src of various elements = to the blob url without luck.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
blah
<script src="https://github.com/foliojs/pdfkit/releases/download/v0.11.0/pdfkit.standalone.js"></script>
<script src="https://github.com/devongovett/blob-stream/releases/download/v0.1.3/blob-stream.js">
</script>
</head>
<body>
<script>
const doc = new PDFDocument
const stream = doc.pipe(blobStream())
doc.fontSize(25).text('Testing document', 100, 80);
console.log(doc);
doc.end();
stream.on('finish', function() {
window.src = stream.toBlobURL('application/pdf');
const a = document.createElement('a');
a.href = stream.toBlobURL('application/pdf');
a.download = 'ShoppingList' || 'download';
console.log("download IS",a)
});
</script>
</body>
</html>
In addition to setting the window.src I have tried document.src iframe.src which returns an error.
displaying isn't strictly necessary but a download link would be. Is there some other way I can do this to get this data? I feel I am missing something very simple.
I have had to change the examples as given on [http://pdfkit.org/docs/getting_started.html][2] but I don't think this is any issue as the package is working as expected and the document is being created.
Edit:
I have made some progress on this but am getting stuck in downloading it. What I did was these 2 things.
<input type="button" id = "dload" onclick="location.href='';" value="Download Shopping List" />
document.getElementById("dload").onclick = function(){location.href = stream.toBlobURL('application/pdf')};
the pdf actually shows in the iframe as expected with the full capabilities of a pdf preview however the download doesn't work at all it just says failed - network error and the filetype is not a pdf which makes sense. Is there something else I can add to get this working?
Edit2: Tried one more thing that doesn't work very well since popups are mostly blocked
window.open(stream.toBlobURL('application/pdf'), '_blank');
this, while it technically works is really messy and is causing a number of problems. Also it works differently on mobile vs desktop. There has to be some simple way to just show a pdf but it seems to just result in more questions the more I search.
[1]: https://i.stack.imgur.com/le6o9.png
[2]: http://pdfkit.org/docs/getting_started.html
I have partially solved my question and it is good enough for what I need. Here is what I did.
<html>
<head>
<script src="https://github.com/foliojs/pdfkit/releases/download/v0.11.0/pdfkit.standalone.js"></script>
<script src="https://github.com/devongovett/blob-stream/releases/download/v0.1.3/blob-stream.js"></script>
<script type="text/javascript">
window.onmessage = (event) => {
if (event.data) {
// create a document and pipe to a blob
var doc = new PDFDocument();
var stream = doc.pipe(blobStream());
doc.font('Helvetica');
doc.fontSize(20);
doc.text('Some Text',200,20);
// end and display the document in the iframe to the right
doc.end();
stream.on('finish', function() {
const blob = stream.toBlob('application/pdf')
const a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = "YourFileName";
a.style.position = 'fixed';
a.target = '_blank';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
};
};
</script>
</head>
<body>
</body>
</html>
while I can't see the pdf using this method it does download correctly which was the more important piece. Technically I could combine the two but since the download button on the iframe doesn't work I think it would be confusing for someone having a separate button to actually download it. So I have a separate button outside the frame that triggers the "onmessage" it is a function of wix. This triggers all document generation and download.

AMR audio not playing in browser, html generated via javascript

Via javascript, I am trying to create the HTML and play an audio file but it's not playing.
If I download that same file and play it via a media player, it plays. My attempt is as below.
var audio = document.createElement("audio");
audio.src = "/files/chat-space/4928f76ff3258fcca32bb75d5d043237";
audio.play();
Is there any way to play this audio inside the browser, even using some other js-supported media player?
Writing the error you're receiving by #ZeroWorks comment would make it much easier, and without an actual example I can only answer it as a guess.
I assume the error you're getting is "play() failed because the user didn't interact with the document first."
I don't know what you're trying to do, but one solution for that could be 'forcing' the client to interact with the document using a button element.
For example:
<script>
function onClick() {
var audio = document.createElement("audio");
audio.src = "./mediaFile.mp3";
audio.play();
}
</script>
Then have the following button element:
<button onclick="onClick()"> Click me </button>
If this is not your issue please try to explain it more precisely.
You can use Audio class in JS
var audio = new Audio('audio_file.mp3'); // file must be having mp3 format
audio.play();
Try:
<script type="text/javascript">
window.addEventListener('load', () => {
var audio = document.createElement("audio");
var asrc = document.createElement("source");
asrc.setAttribute('src', "/files/chat-space/4928f76ff3258fcca32bb75d5d043237");
audio.appendChild(asrc);
audio.play();
});
</script>
Notes:
The window.addEventListener('load') tells the page not to try playing the audio until all HTML and resources are loaded/available.
The audio tag does not have a src= attribute — it has a child element, <source>, and that element has the src= attribute.
FWIW, I just tested the above code on a live server, using a standard mp3 audio file. If this code does not work for you, first try it with a standard .mp3 file (to ensure the problem is not with specifying the audio file).
If it still doesn't work, please tell us more about your environment.
See:
https://www.w3schools.com/TAGS/tag_audio.asp

How to load an image generated by an aspx file into html

The following image: http://www.oscn.net/dockets/GetDocument.aspx?ct=tulsa&cn=SC-2011-361&bc=1014242988&fmt=tif
How would I go about downloading this image and displaying it in html using javascript?
Here you go..
If you need to modify any properties of the image (size/color enhancement/etc.) use new_elem.setAttribute('attribute', 'value'); Just like in HTML <img attribute="value" />
var element = document.getElementById('mytargetlocation');
var new_elem = document.createElement('img');
var locationtoimage = 'https://www.sourcecertain.com/img/Example.png';
/*
Note: if your site uses HTTPS, this file will need to be loaded
over HTTPS, if it doesn't, you could just use the original
URL without downloading the image at all
*/
new_elem.setAttribute('src', locationtoimage);
new_elem.setAttribute('alt', 'image not found at specified URL');
element.append(new_elem);
<div id="mytargetlocation"></div>

HTML, how to set multiple src attributes for image in parallel, fastest win

I want to asynchronously download image, so first user sees a low resolution image, and higher resolution version is downloaded in the background. I have tried the following.
<html>
<head>
<script>
window.addEventListener('load', function () {
var kuvaEl = document.getElementById('kuva');
var r_src = kuvaEl.getAttribute('r-src');
var a_src = kuvaEl.getAttribute('a-src');
kuvaEl.setAttribute('src', r_src);
kuvaEl.setAttribute('src', a_src);
});
</script>
</head>
<body>
<img id="kuva" src="http://www.viikonloppu.com/wp-content/uploads/2014/04/lotoflaughters.com_-619x428.jpg?c3bc1b"
a-src="https://www.manitowoccranes.com/~/media/Images/news/2014/Potain-China-hi-res.jpg"
r-src="http://fuzyll.com/images/2016/angel_oak_panorama.jpg" />
</body>
</html>
But the problem is r_src download is aborted when src is change second time. I want to download both of these images in parallel, and show the r_src first (only if it downloads faster than a_src), and when the *a_src *is ready, show the a_src.
Also, is it possible to download these a_src and r_src images to the browser cache before the src is actually changed? Ideally I would like the the src change to either retrieve the image from the cache or join the pending download for that url.
I can also use jQuery. IE7 must support the implementation.
You just need to use javascript or jquery and load two version of the same image. the first will be your low res, but you will download a high res inside an hidden img tag.
When the download is complete, you just hide / delete the low res image and show the high res.
This link show some test and few way to do it. And it should support ie7 Load a low-res background image first, then a high-res one
You can use interlaced progressive JPEG format.
This method is the preferred method for handling high quality images and has been implemented by so many websites.the idea is that the compression of the image is made in such away that the when you send the image the receiver gets the image in finer and finer detail has the sending of the data progressed.
if you dont want to use the abouve technique
Have the low quality image in the src of the image. once the whole page loaded successfully,change the low quality image with high quality image
<img id="target-image" src="low-quality.jpg" data-src="high-quality.jpg" />
$(window).load(function(){
var imgSrc = $('#target-image').data('src');
$('#target-image').attr('src',imgSrc);
});
You should put your low res as default src. Then use JS to download the high res version and on download completion, change image src.
Also, good practice is to use data-* for custom attributes
If your really want a parallel download, you should replace "load" event for the "DOMContentLoaded" event. However, this will extend the time your user has to wait until page is ready. Your should keep the load event to prioritize critical assets loading (scripts and stylesheets)
window.addEventListener('load', function() {
// get all images
let images = document.getElementsByClassName("toHighRes");
// for each images, do the background loading
for (let i = 0; i < images.length; i++) {
InitHighResLoading(images[i]);
}
});
function InitHighResLoading(image) {
let hrSrc = image.dataset["hr"];
let img = new Image();
img.onload = () => {
// callback when image is loaded
image.src = hrSrc;
}
// launch download
img.src = hrSrc;
}
img {
/* only for code snippet */
max-height: 300px;
}
<img class="toHighRes"
data-hr="https://www.manitowoccranes.com/~/media/Images/news/2014/Potain-China-hi-res.jpg"
src="http://fuzyll.com/images/2016/angel_oak_panorama.jpg" />

Create live preview of image (before upload it) using JQuery

I want to create a preview for image before upload it on the server, using JQuery.
My code, js code:
$(function(){
Test = {
UpdatePreview: function(obj){
// if IE < 10 doesn't support FileReader
if(!window.FileReader){
// don't know how to proceed to assign src to image tag
} else {
var reader = new FileReader();
var target = null;
reader.onload = function(e) {
target = e.target || e.srcElement;
$("img").prop("src", target.result);
};
reader.readAsDataURL(obj.files[0]);
}
}
};
});
My html:
<input type='file' name='browse' onchange='Test.UpdatePreview(this)' />
<br/><br/>
<img src="#" alt="test" width="128" height="128" />
See jsfiddle: http://jsfiddle.net/aAuMU/
After onload, I see the src of image (using Google console application) and it looks like:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD//gAEKgD/4gv4SUNDX1BST0ZJTEUAAQEAAAvoAAAAAAIAAABtbnRyUkdCIFhZWiAH2QADABsA...
It is a way to get in javascript the base of image and assign to image in case I'm using IE as browser ?
FileReader doesn't work in IE < 10.
If you need it as getting nice effect then you could use flash like they do in
https://github.com/mailru/FileAPI
But when i needed to show image to user because i needed to let user select area for croping then i used form inside hidden iframe and uploaded image to server and sent back image data uri so i was able to get data uri and replace image src attribute, then when area was selected i did not send image back as file but as data uri. In old browsers it means you upload image twice, but i did not want to use flash as in some cases flash may also not be installed there.
LIVE PREVIEW CAN BE DONE IN JQUERY
We need an onchange event to load the image. img tag is given an id = frame, the function UpdatePreview() loads the image immediately after the image or file is selected.
function UpdatePreview(){
$('#frame').attr('src', URL.createObjectURL(event.target.files[0]));
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input type='file' name='browse' oninput='UpdatePreview()'/>
<img src="#" id ="frame" alt="test" width="128" height="128" />
Instead of
$("img").prop("src", target.result);
write
$("#ImageId").attr("src", target.result);
Where ImageId is the ID of your img tag.

Categories