SoundJS Not Working After Upload - javascript

I'm attempting to add sound to my HTML5 game using SoundJS, a free Javascript library (http://www.createjs.com/#!/SoundJS).
I'm testing it out using the most basic sample program that's included in the zip. It runs great when opening in a browser from my hard drive, but after uploading it, no sounds play when I load the page from the web. The sound files are in the exact same place and folder as on my pc.
Has anyone successfully gotten this to work?
Here's what I'm trying to run:
function init()
{
if (!createjs.Sound.initializeDefaultPlugins()) {return;}
var audioPath = "sounds/";
var manifest = [
{id:"Music", src:"18-machinae_supremacy-lord_krutors_dominion.ogg"},
{id:"Thunder", src:"Thunder1.ogg"}
];
createjs.Sound.alternateExtensions = ["mp3"];
createjs.Sound.addEventListener("fileload", handleLoad);
createjs.Sound.registerManifest(manifest, audioPath);
}
function handleLoad(event)
{
createjs.Sound.play(event.src);
}

I work on SoundJS and can confirm it works from servers, as you can see in the examples.
As the above comment says, the best place to start is in developer console in your browser.
Potential sources of the issue are not including or having the wrong path for the js files that are loaded in the script tags, not including / wrong path for the sound files, and possibly but unlikely not setting the correct mime types on your server to properly return audio files.
Hope that helps.

Related

Copy/download temporary files

I am not an HTML/JavaScript developer. I am having to modify some legacy code written by someone who has left.
We have a Python app which acts as a local server with an HTML/JavaScript front end that can be viewed in a browser.
The Python creates a temporary cache file. I would like to give the user the option to save a copy of this temp file to a location of their choice or at least download it to the downloads directory (Windows & Linux)
I've tried adapting some of the ideas from here: https://www.delftstack.com/howto/javascript/javascript-download/
E.g.
const saveAnalysisBtn = document.getElementById("saveAnalysisBtn");
saveAnalysisBtn.addEventListener('click', saveAnalysis);
function saveAnalysis(evt) {
function download(filename) {
var element = document.createElement('a');
// hardcode temp file name just for POC
element.setAttribute('href','file://C:\\tmp\\my_temp_cache.db');
element.setAttribute('download', filename);
document.body.appendChild(element);
element.click();
//document.body.removeChild(element);
}
var filename = "output.txt";
console.log(`Call Download`);
download(filename);
}
In Firefox this gives a security error:
Security Error: Content at
http://127.0.0.1:5000/replay/fapi_15_6_udi.bin may not load or link to
file:///C:/tmp/my_temp_cache.db
Which isn't terribly surprising. (Edge & Chrome give similar errors)
Is there a way to do this? Can be in HTML or JavaScript or Python (though I would like user to see evidence of download taking place in the browser).
Maybe I'm not understanding, but it looks like we're talking about just copying a file from one local location to a user specified location. The file you want to copy is on the machine the user is using? Couldn't you just provide the location in the web page and then just go there in a file explorer, finder, or command line tool to copy it however you want? It would solve the security issue.
But if you're required to create a link, you could create a download process that zips the file up to make a file like "my_temp_cache_db.zip" (or whatever compression tool/extension works best for you), and then provide the link for that. Zip files work through browsers better than some other types of files, and the user just has to unzip it wherever it ended up.
If that's not ideal, you could create a download process that makes a copy of the file and just changes the extension to something like "txt". The user downloads that file and then has to rename it to have the right extension.

How to store and load/display local PDFs with browser-data, from a website

I'm working with an extremely old database system containing people and associated PDFs. I can access most data over a webbrowser, however PDFs cannot be requested via web-api - I do however have the liberty of loading any javascript library, and use chrome webdev console.
I want to get a proof of principle working, where I can load a person's PDFs. But I'm not quite sure what the best approach is.
Idea to upload a file to the website's local storage in my browser (since it's viewed several times). However I seem to be lacking a good library to save/load files from the cache directory. This library wasn't updated since 2016 and Filesaver.js doens't seem to be keen on loading the files after saving. Using a fully-fledged database implementation seems overkill (most files will be <= 5-10MB)
Loading a file from local storage (even if dir is added to workspace in chrome) seems completely impossible, that would've been an alternative
adding the local file path to a <a href=""> element did not work in chrome
Is there a feasible approach to manage/associate PDF files on my local drive with the website I'm working with (and have full client-side control, i.e. can load any library)?
Note: Access is restricted, no chrome addons can be used and chrome cannot be started using custom flags
I don't exactly know what you are asking for, but this code will get all the pdfs in a selected directory and display them and also makes a list of all the file objects. This will only work in a "secure context" and on chrome
(it also wont run in a sandbox like a stackoverflow code snippet)
js
let files = [];
async function r() {
for await (const [_, h] of (await window.showDirectoryPicker()).entries()) files.push(await h.getFile());
files = files.filter(f => f.type === "application/pdf");
for (const f of files) {
let e = document.createElement("embed");
e.src = URL.createObjectURL(f), e.type = f.type;
document.body.appendChild(e);
}
}
html
<button onclick="r()">read PDFs</button>
also you can probably use this if you need to send the local PDF somewhere
not sure this answers the question but i hope it helps
Since ActiveX controls are no longer available browsers can display a PDF or a user can download the pdf.
For any more control over that I suspect you could try render the pdf using a JavaScript library like https://mozilla.github.io/pdf.js/
For full control you wont be in a position to control the PDF version, you could alternatively render the PDFs to images on the server and display image versions of the pages.

Does not download a file by magnet links

This is an example from the documentation.
var client = new WebTorrent()
var torrentId = 'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel.torrent'
client.add(torrentId, function (torrent) {
// Torrents can contain many files. Let's use the .mp4 file
//var file = torrent.files.find(function (file) {
//return file.name.endsWith('.mp4')
//})
// no console.log !!
console.log(torrent)
// Display the file by adding it to the DOM. Supports video, audio, image, etc. files
torrent.files[0].appendTo('body')
})
An example works well.
But if I change the magnet link to another but nothing happens.
The link to which I am changing is valid.
magnet:?xt=urn:btih:C45CE38E4508E775E49EB2A6841C814D1A8AD375&tr=http%3A%2F%2Fbt3.t-ru.org%2Fann%3Fmagnet
but does not work with this link. Not a single mistake or nothing at all
I have had similar issues recently trying to work this out. Only instant.io (using a turn server) consistently works. Very little webRTC stuff works for me.
I think the reason the template provided by WebTorrent works and no others is because the model contains a magnet which has a link to the torrent file on their website.
I suspect they are seeding it or even just providing it via some other means.
xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel.torrent
Whoever created instant.io took the web torrent template and made it work. WebRTC is an absolute nightmare, and the web torrent template/site doesn't even get the WebSocket connections right (for me, at least).
If you are looking to pass on relatively small amounts of data, then relaying via your WebSockets is far more manageable.
If you want to create something like WebTorrent, that works look at instant.io's Github. You'll need to set up a server and configure a turn server. WebRTC is like trying to configure a graphics card in 1992. Good luck.

How to Launch a PDF from a UWP (Universal Windows Platform) Web Application

I've converted an existing web application (HTML5, JS, CSS, etc.) into a Windows UWP app so that (hopefully) I can distribute it via the Windows Store to Surface Hubs so it can run offline. Everything is working fine, except PDF viewing. If I open a PDF in a new window, the Edge-based browser window simply crashes. If I open an IFRAME and load PDFJS into it, that also crashes. What I'd really like to do is just hand off the PDF to the operating system so the user can view it in whatever PDF viewer they have installed.
I've found some windows-specific Javascript APIs that seem promising, but I cannot get them to work. For example:
Windows.System.Launcher.launchUriAsync(
new Windows.Foundation.Uri(
"file:///"+
Windows.ApplicationModel.Package.current.installedLocation.path
.replace(/\//g,"/")+"/app/"+url)).then(function(success) {
if (!success) {
That generates a file:// URL that I can copy into Edge and it shows the PDF, so I know the URL stuff is right. However, in the application it does nothing.
If I pass an https:// URL into that launchUriAsync function, that works. So it appears that function just doesn't like file:// URLs.
I also tried this:
Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(url).then(
function(file) { Windows.System.Launcher.launchFileAsync(file) })
That didn't work either. Again, no error. It just didn't do anything.
Any ideas of other things I could try?
-- Update --
See the accepted answer. Here is the code I ended up using. (Note that all my files are in a subfolder called "app"):
if (location.href.match(/^ms-appx:/)) {
url = url.replace(/\?.+/, "");
Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(("app/" + url).replace(/\//g,"\\")).then(
function (file) {
var fn = performance.now()+url.replace(/^.+\./, ".");
file.copyAsync(Windows.Storage.ApplicationData.current.temporaryFolder,
fn).then(
function (file2) {
Windows.System.Launcher.launchFileAsync(file2)
})
});
return;
}
Turns out you have to turn the / into \ or it won't find the file. And copyAsync refuses to overwrite, so I just use performance.now to ensure I always use a new file name. (In my application, the source file names of the PDFs are auto-generated anyway.) If you wanted to keep the filename, you'd have to add a bunch of code to check whether it's already there, etc.
LaunchFileAsync is the right API to use here. You can't launch a file directly from the install directory because it is protected. You need to copy it first to a location that is accessible for the other app (e.g. your PDF viewer). Use StorageFile.CopyAsync to make a copy in the desired location.
Official SDK sample: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/AssociationLaunching
I just thought I'd add a variation on this answer, which combines some details from above with this info about saving a blob as a file in a JavaScript app. My case is that I have a BLOB that represents the data for an epub file, and because of the UWP content security policy, it's not possible simply to force a click on a URL created from the BLOB (that "simple" method is explicitly blocked in UWP, even though it works in Edge). Here is the code that worked for me:
// Copy BLOB to downloads folder and launch from there in Edge
// First create an empty file in the folder
Windows.Storage.DownloadsFolder.createFileAsync(filename,
Windows.Storage.CreationCollisionOption.generateUniqueName).then(
function (file) {
// Open the returned dummy file in order to copy the data to it
file.openAsync(Windows.Storage.FileAccessMode.readWrite).then(function (output) {
// Get the InputStream stream from the blob object
var input = blob.msDetachStream();
// Copy the stream from the blob to the File stream
Windows.Storage.Streams.RandomAccessStream.copyAsync(input, output).then(
function () {
output.flushAsync().done(function () {
input.close();
output.close();
Windows.System.Launcher.launchFileAsync(file);
});
});
});
});
Note that CreationCollisionOption.generateUniqueName handles the file renaming automatically, so I don't need to fiddle with performance.now() as in the answer above.
Just to add that one of the things that's so difficult about UWP app development, especially in JavaScript, is how hard it is to find coherent information. It took me hours and hours to put the above together from snippets and post replies, following false paths and incomplete MS documentation.
You will want to use the PDF APIs https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/PdfDocument/js
https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/PdfDocument/js/js/scenario1-render.js
Are you simply just trying to render a PDF file?

How to open a local PDF in a Windows 8/Cordova app?

I have an IOS app that I built which now I've been tasked to port over to Windows 8 for use on the Windows tablet. My app downloads files from Dropbox, which gets stored in the Local folder. I can see all of that works fine. I am able to reference images by using ms-appdata:///local/" + filename in the src of my img tag, and I'm even able to play mp4s from the same folder using HTML5 video tags.
My problem is, for my IOS version, I was using Cordova's InAppBrowser to open local PDFs but on this Windows 8 version, it doesn't work.
I am using the following code (filename equals [1]CaseStudy-AC_EN_04.pdf and it does exist on the file system):
var ref = window.open("ms-appdata:///local/" + filename, '_blank', 'location=no');
And I get the following error in Visual Studio when I run the Simulator
APPHOST9607: The app can't launch the URI at ms-appdata:///local/[1]CaseStudy-AC_EN_04.pdf because of this error: -2147024846.
I've tried switching to WinJS coding methods, even tried loading the PDF in an iFrame but nothing will work. I don't mind kicking the user out to Internet Explorer if I must... I just need some way for the user to see these local PDFs. Is this a permissions issue? I only have a config.xml file and not a app manifest file, so perhaps I'm missing a setting?
Does anyone have experience with this?
In case anyone else has this issue. I was able to do what I wanted with this WinJS code (make sure you include the WinJS framework file)
//this is just the filename, you can probably skip this step but my filenames are from downloaded files so they could be encoded.
fileName = decodeURIComponent(fileName);
//get the local folder that contains the downloaded files
var applicationData = Windows.Storage.ApplicationData.current;
var localFolder = applicationData.localFolder;
//grab the file and return a promise
localFolder.getFileAsync(fileName)
.then(function(file) {
//launch the file - this command will let the OS use it's default PDF reader - win 8 app 'reader' works great.
Windows.System.Launcher.launchFileAsync(file);
});
That's it.
#Matthew Corway works fine.
But, need aditional attention when the file is within a subfolder as follow exemple:
var fullPath = "\folderName\fileName.pdf"

Categories