Get Audio File Duration Via a Microsoft DLL or Utility - audio

Is there a Windows dll or utility that can be used to see the duration (HH:MM:SS) of an audio file (WMA, MP3, or WAV) that can be accessed from a script (specifically JScript)?
I know there is one, or something else can read file metadata, but I'm unfamiliar with it.

You can use the GetDetailsOf method of the Windows Shell Folder object to get the audio file length. This technique supports all audio file types whose metadata can be read and displayed by Windows Explorer natively.
However, note that the index of the Length attribute is different on different Windows versions: it's 21 on Windows XP/2003 and 27 on Windows Vista+. See this page and this my answer for details. You will need to take this into account in your script.
Example code:
var LENGTH = 27; // Windows Vista+
// var LENGTH = 21; // Windows XP
var oShell = new ActiveXObject("Shell.Application");
var oFolder = oShell.Namespace("C:\Music");
var oFile = oFolder.ParseName("Track.mp3");
WScript.Echo(oFolder.GetDetailsOf(oFile, LENGTH));
Example output:
00:05:18

Related

Python: Access photos on iPhone for Exif Data

I am looking to access all photos on my iPhone using Python.
I want to be able to exract the Exif data to load into Leaflet / Folium.
It would seem that I cannot access the path for the photos because the phone is connected using a MTP Connection.
I found a script and managed to modify it to allow me to list all photos on the phone in the DCIM directory.
for pidl in folder.EnumObjects(0, shellcon.SHCONTF_NONFOLDERS):
name = folder.GetDisplayNameOf(pidl, shellcon.SHGDN_FORADDRESSBAR)
dirname = os.path.dirname(name)
basename, ext = os.path.splitext(os.path.basename(name))
#print (name)
#print (dirname)
#print (basename)
if ext.endswith("JPG") and i == 1:
photo_dict[dirname].append(name)
i =+ 1
print (photo_dict[dirname][0])
I am access the path to the image, but when I try and open the image using PIL, I receive an error that the path does not exist. Which I am guessing is due to the MTP connection and the way that interacts with the File Explorer.
How can I process imagery using the path provided by my script, is there a better method?
I want to keep the files on the phone, so copying off is not an option.
I am using Python 3.5 and Windows 10.

Somtime issues when Read csv data config from jmeter

I have an issue when creating a performance script, which has related to reading data from csv data config.
My script has a structure below:
setup Thread
Create csv Thread. After view dashboard, using Json extractor to get list of data and put it to csv file
Create csv file - After this thread, i will have a lot of csv file base on number of center. For example: 4 files with different names
String[] attempt = (vars.get("ListAttemptId_ALL")).split(",");
int length = attempt.length;
String dir = props.get("UserFilePath").toString();
String center = vars.get("Center");
File csvFile = new File(dir, center + ".csv");
if(!csvFile.exists()){
FileWriter fstream = new FileWriter(csvFile);
BufferedWriter out = new BufferedWriter(fstream);
for(int i = 1; i <= length; i++){
out.write(attempt[i-1]);
out.write(System.getProperty("line.separator"));
}
out.close();
fstream.close();
}
Next thread gets the name of the file and using CSV file to loop over
all line
String center = vars.get("Center");
String fileName = center + ".csv";
props.put("path_${__threadNum}", String.valueOf(fileName));
Because i have alot of threads will run the same file, so i just check __threadNum of to find the name of the file this thread need to use.
I'm using loop Controller to go over CSV file, run to the end of the file will stop thread. Here is inside this loop
CSV data Set config:
Filename: ${__property(UserFilePath)}\\${__P(path_${__threadNum})}
where ${__property(UserFilePath)} = path of the folder and
${__P(path_${__threadNum})} is name of the csv file were extracted
My issue is this code is not stable, sometimes threads can read file normally, sometimes it's show error that file does not exist (actually it did) so it's hard to chase that where issue from. Can anyone suggest a solution to my issue? Or suggest any idea better than my solution to read csv file in thread group?
I have answer for this issue:
- I add all data AttemptId, Center to one file csv and read from beginning to and end. Using If controller to verify data before action.
This statement can be problematic:
props.put("path_${__threadNum}", String.valueOf(fileName));
as per JSR223 Sampler documentation
JMeter processes function and variable references before passing the script field to the interpreter, so the references will only be resolved once. Variable and function references in script files will be passed verbatim to the interpreter, which is likely to cause a syntax error. In order to use runtime variables, please use the appropriate props
methods, e.g.
props.get("START.HMS");
props.put("PROP1","1234");
So I would recommend replacing ${__threadNum} with ctx.getThreadNum() where ctx is a shorthand for JMeterContext class
According to Execution Order chapter of JMeter Documentation:
0. Configuration elements
1. Pre-Processors
2. Timers
3. Sampler
4. Post-Processors (unless SampleResult is null)
5. Assertions (unless SampleResult is null)
6. Listeners (unless SampleResult is null)
your CSV Data Set Config is executed at the first place, before any other scripting test elements. So the times when it "works" IMO are being caused by "false positive" situation as JMeter Properties are global and "live" while JMeter (and underlying JVM) is running. When you launch JMeter next time the properties will be null and your CSV Data Set Config will fail. So my expectation is that you should consider using __CSVRead() function instead which is evaluated in the runtime exactly in the place where it's being called. Check out Apache JMeter Functions - An Introduction article to learn more about JMeter Functions concept.

Backup Google Drive to .zip file with file conversion

I keep going in circles on this topic, and can't find an automated method that works for mass data on a Google Drive. Here is the goal I'm looking to achieve:
My company uses an unlimited Google Drive to store shared documents, and we are looking to backup the contents automatically. But we can't have the data stored in a backup with google documents like ".gdoc" and ".gsheet"... we need to have the documents backed up in Microsoft/Open-Office format (".docx" and ".xlsx").
We currently use Google's Takeout page to zip all the contents of the Drive and save it on our Linux server (That has redundant storage). And it does zip and export the files to the correct formats.
Here: [https://takeout.google.com/settings/takeout][1]
Now that works... but requires a bit of manual work on our part. And babysitting the zip, download and upload processes is becoming wasteful. I have searched and have read that the google API for Takeout is unavailable to use through gscript. So, that seems to be out of the question.
Using Google scripts, I have been able to convert single files.... but can't, for instance, convert a folder of ".gsheet" files to ".xlsx" format. Maybe copying and converting all the google files into a new folder on the drive could be possible. Having access to the drive and the converted "backup", we could then backup the collection of converted files via the server...
So here is the just of it all:
Can you mass-convert all of a google drive and/or a specific folder on the drive from ".gdoc" to ".docx", and ".gsheet" to ".xlsx". Can this be done with gscript?
If not able to via the method in question one, is anyone familiar with an Linux of Mac app that could do such a directory conversion? (Don't believe it because of googles proprietary file types)
I'm stuck in a bit of a hole, and any insight to this problem could help. I really wish Google would allow users to convert and export drive folders via a script selection.
#1) Can you mass-convert all of a google drive and/or a specific folder on the drive from ".gdoc" to ".docx", and ".gsheet" to ".xlsx". Can this be done with gscript?
You can try this:
How To Automaticlly Convert files in Google App Script
Converting file in Google App Script into blob
var documentId = DocumentApp.getActiveDocument().getId();
function getBlob(documentId) {
var file = Drive.Files.get(documentId);
var url = file.exportLinks['application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
var oauthToken = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + oauthToken
}
});
return response.getBlob();
}
Saving file as docx in Drive
function saveFile(blob) {
var file = {
title: 'Converted_into_MS_Word.docx',
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
};
file = Drive.Files.insert(file, blob);
Logger.log('ID: %s, File size (bytes): %s', file.id, file.fileSize);
return file;
}
Time-driven triggers
A time-driven trigger (also called a clock trigger) is similar to a cron job in Unix. Time-driven triggers let scripts execute at a particular time or on a recurring interval, as frequently as every minute or as infrequently as once per month. (Note that an add-on can use a time-driven trigger once per hour at most.) The time may be slightly randomized — for example, if you create a recurring 9 a.m. trigger, Apps Script chooses a time between 9 a.m. and 10 a.m., then keeps that timing consistent from day to day so that 24 hours elapse before the trigger fires again.
function createTimeDrivenTriggers() {
// Trigger every 6 hours.
ScriptApp.newTrigger('myFunction')
.timeBased()
.everyHours(6)
.create();
// Trigger every Monday at 09:00.
ScriptApp.newTrigger('myFunction')
.timeBased()
.onWeekDay(ScriptApp.WeekDay.MONDAY)
.atHour(9)
.create();
}
Process:
List all files id inside a folder
Convert Files
Insert Code to a Time-driven Triggers
2) If not able to via the method in question one, is anyone familiar with an Linux of Mac app that could do such a directory conversion? (Don't believe it because of googles proprietary file types)
If you are want to save it locally try setting a cronjob and use Download Files
The Drive API allows you to download files that are stored in Google Drive. Also, you can download exported versions of Google Documents (Documents, Spreadsheets, Presentations, etc.) in formats that your app can handle. Drive also supports providing users direct access to a file via the URL in the webViewLink property.
Depending on the type of download you'd like to perform — a file, a Google Document, or a content link — you'll use one of the following URLs:
Download a file — files.get with alt=media file resource
Download and export a Google Doc — files.export
Link a user to a file — webContentLink from the file resource
Sample Code :
$fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M';
$content = $driveService->files->get($fileId, array(
'alt' => 'media' ));
Hope this helps and answered all you questions

how to draw shapes in a PDF using NodeJS

I have some existing PDF files and what I want is to highlight some content by overlaying circles or straight lines. I've looked at some NodeJS PDF libraries but couldn't find a solution (some libraries allow creating a PDF from scratch and draw into it; other libraries can modify existing PDFs, but do not support drawing).
A (Linux / OSX) command line solution (e.g. using ImageMagick or some other library) would be perfectly fine, too.
Edit I've since found out that with Image/GraphicsMagick I can in fact do sth. like gm convert -draw "rectangle 20,20 150,100" xxx.pdf[7] xxx2.pdf, but this (1) either draws on all pages or else only on a single one, but then the resulting PDF will only contain that page; (2) the output PDF will contain a bitmap image where I would prefer a PDF with text content.
Edit I've just found HummusJS which is a NodeJS library to manipulate PDF files via declarative JSON objects. Unfortunately, apart from the scrace documentation, the unwieldy API (see below), the tests fail consistently and across the board with Unable to create PDF file, make sure that output file target is available.
completely OT not sure what it is that makes people think such utterly obfuscated APIs are better than simple ones:
var settings = {modifiedFilePath:'./output/BasicJPGImagesTestPageModified.pdf'}
var pdfWriter = hummus.createWriterToModify('./TestMaterials/BasicJPGImagesTest.PDF',settings);
var pageModifier = new hummus.PDFPageModifier(pdfWriter,0);
pageModifier.startContext().getContext().writeText('Test Text', ...
...
var copyingContext = inPDFWriter.createPDFCopyingContextForModifiedFile();
var thirdPageID = copyingContext.getSourceDocumentParser().getPageObjectID(2);
var thirdPageObject = copyingContext.getSourceDocumentParser().parsePage(2).getDictionary().toJSObject();
var objectsContext = inPDFWriter.getObjectsContext();
objectsContext.startModifiedIndirectObject(thirdPageID);
var modifiedPageObject = inPDFWriter.getObjectsContext().startDictionary();
A couple of helpers with HummusJS, to assist with what you are trying to do:
Adding content to existing pages - https://github.com/galkahana/HummusJS/wiki/Modification#adding-content-to-existing-pages
Draw shapes - https://github.com/galkahana/HummusJS/wiki/Show-primitives
using both, this is how to add a circle at 'centerx,centery' with 'radius' and border width of 1, to the first page of 'myFile.pdf'. The end result, in this case will be placed in 'modifiedCopy.pdf':
var pdfWriter = hummus.createWriterToModify(
'myfile.pdf',
{modifiedFilePath:'modifiedCopy.pdf'});
var pageModifier = new hummus.PDFPageModifier(pdfWriter,0);
var cxt = pageModifier.startContext().getContext();
cxt.drawCircle(
centerX,
centerY,
radius,
{
type:stroke,
width:1,
color:'black'
});
pageModifier.endContext().writePage();
pdfWriter.end();
General documentation - https://github.com/galkahana/HummusJS/wiki
If the tests fail, check that an "output" folder exists next to the script being executed, and that there are permissions to write there.

VLCJ: Time code missing when saving a video stream from an embedded media player

I have an application that shows a video stream from a camera, and is able to save the video stream on a file on request. When I run this command from the terminal I see the video in VLC, and the contents is saved on a file as expected:
vlc v4l:///dev/video0:norm=ntsc ':sout=#duplicate{dst=display{noaudio},dst="transcode{vcodec=wmv2,vb=800}:file{dst=aaa.wmv}"}'
However, when I save a file from my application the there are no time codes in the file, so when I open the file in another application I'm unable to move backwards or forwards in the file. I can also not see how long the file is.
Here is a simplified version of my code
factory = new MediaPlayerFactory();
mainframe = new JFrame("Video Viewer");
fullscreenStrategy = new DefaultFullScreenStrategy(mainframe);
Canvas canvas = new Canvas();
canvas.setBackground(Color.black);
EmbeddedMediaPlayer player= factory.newEmbeddedMediaPlayer(fullscreenStrategy);
mainframe.add(canvas);
player.setVideoSurface(factory.newVideoSurface(canvas));
...
String media = "v4l:///dev/video0:norm=ntsc";
String filename = "aaa.wmv";
String mediaoptions = ":sout=#duplicate{ dst=display,"+
" dst=\"transcode{vcodec=wmv2,vb=800}:"+
"file{dst="+filename+"}\"}");
player.prepareMedia(media, mediaoptions);
player.start();
aaa.wmv is created, but without time codes.
What can be wrong? The only difference I see from the command line version is that I use a Canvas widget with the EmbeddedMediaPlayer instead of the native VLC view window.
Never mind, I found the problem. For the time codes to be saved properly it is necessary to call player.release(). I did that, but before the release call I copied the file to another location. Since release hadn't been called yet the file was incomplete. When I changed the code to first call player.release(), then copy the file it worked as expected.

Resources