Get date added of Finder items in Applescript - applescript

I can get files by date modified using this bit of code:
get (files of entire contents of folder "Macintosh HD:General Music:05 Reggae:" whose modification date is less than ((current date)) - modDate * days)
but I can't seem to get their date added (nor is it listed in Applescript dictionary for Finder that I can see). This is weird, 'cause I can do a smart folder that uses this property.
Any idea on how to get files who were added within 15 days? Otherwise I'm doing loads of weird stuff with GUI at the moment and I'd like to automate it further.
Thanks
Tardy

You can search Spotlight's metadata with the mdfind command, use the kMDItemDateAdded key:
set _15daysAgo to -15 * days -- number of seconds
set tFolder to quoted form of POSIX path of "Macintosh HD:General Music:05 Reggae:"
-- find files, not folders
do shell script "mdfind -onlyin " & tFolder & " 'kMDItemDateAdded>$time.now(" & _15daysAgo & ") && ! kMDItemContentType == public.folder'"
set tFiles to paragraphs of the result
repeat with i in tFiles
tell i to set contents to i as POSIX file as alias
end repeat
tFiles -- list of files who were added within 15 days
Or, use the methods of the NSFileManager Class to get the NSURLAddedToDirectoryDateKey of the files (require Yosemite or El Capitan),
Here's the AppleScript:
set _15daysAgo to -15 * days -- number of seconds
set f to POSIX path of "Macintosh HD:General Music:05 Reggae:"
do shell script "/usr/bin/python -c 'import sys; from Foundation import NSFileManager, NSURL, NSDate, NSDirectoryEnumerationSkipsHiddenFiles
def procFolder(tDir):
p = dfM.contentsOfDirectoryAtURL_includingPropertiesForKeys_options_error_(tDir, myKeys, NSDirectoryEnumerationSkipsHiddenFiles, None)[0]
for f in p:
myDict, error=f.resourceValuesForKeys_error_(myKeys, None)
if error is None:
if (myDict.get(\"NSURLIsDirectoryKey\")): procFolder(f)
elif (myDict.get(\"NSURLAddedToDirectoryDateKey\").compare_(d) == 1):
print f.path().encode(\"utf8\")
fold=NSURL.fileURLWithPath_isDirectory_(sys.argv[1].decode(\"utf8\"), True)
dfM=NSFileManager.defaultManager()
d=NSDate.dateWithTimeIntervalSinceNow_(" & _15daysAgo & ")
myKeys=[\"NSURLIsDirectoryKey\", \"NSURLAddedToDirectoryDateKey\"]
procFolder(fold)' " & f
set tFiles to paragraphs of the result
repeat with i in tFiles
tell i to set contents to i as POSIX file as alias
end repeat
tFiles -- list of files who were added within 15 days

Related

Is there a reason my AppleScript is running so slow?

I have a script to run from a command line prompt. The command,
followed by some text, will set a reminder in the Reminder.app with a
due date of next friday. The script is taking about 100 seconds to run
which seem very high.
on nextWeekday(wd)
set today to current date
set twd to weekday of today
if twd is wd then
set d to 7
else
set d to (7 + (wd - twd)) mod 7
end if
return today + (d * days)
end nextWeekday
on run argv
set nextFriday to nextWeekday(Friday)
tell application "Reminders"
set newLable to argv as string
set myList to list "Do."
tell myList
set newReminder to make new reminder
set name of newReminder to newLable
#set remind me date of newReminder to theDay
set allday due date of newReminder to nextFriday
end tell
end tell
end run
The code in the .bash_profile is as follows:
function reme() {
cd
cd /Users/jamieauburn/Documents/projects/reminder
osax reme.scpt $1
}
Have I got something wrong in the script?
You have a lot of unnecessary things here. Your script can be written much more compactly, and it becomes about 4 times faster.
on run argv
tell (current date) to set nextFriday to it + (6 - (its weekday)) * days
tell application "Reminders" to tell list "Do."
make new reminder with properties {name:(argv as string), allday due date:nextFriday}
end tell
end run

I need to URL-encode a string in AppleScript

My script searches a website for songs, but when there are spaces it doesn't search, you have to add underscores. I was wondering if there was a way to replace my spaces with underscores.
Could you please use my current code below to show me how to do it?
set search to text returned of (display dialog "Enter song you wish to find" default answer "" buttons {"Search", "Cancel"} default button 1)
open location "http://www.mp3juices.com/search/" & search
end
Note: The solution no longer works as of Big Sur (macOS 11) - it sounds like a bug; do tell us if you have more information.
Try the following:
set search to text returned of (display dialog "Enter song you wish to find" default answer "" buttons {"Search", "Cancel"} default button 1)
do shell script "open 'http://www.mp3juices.com/search/'" & quoted form of search
end
What you need is URL encoding (i.e., encoding of a string for safe inclusion in a URL), which involves more than just replacing spaces.
The open command-line utility, thankfully, performs this encoding for you, so you can just pass it the string directly; you need do shell script to invoke open, and quoted form of ensures that the string is passed through unmodified (to be URI-encoded by open later).
As you'll see, the kind of URL encoding open performs replaces spaces with %20, not underscores, but that should still work.
mklement0's answer is correct about url encoding but mp3juices uses RESTful URLs (clean URLs). RESTful URLs want's to keep the URL human readable and you won't see/use typical hex values in your url presenting an ASCII number. A snake_case, as you have mentioned (is false), but it is pretty common to use an substitution for whitespaces (%20) (and other characters) in RESTful URLs. However the slug of an RESTful must be converted to RESTful's own RESTful encoding before it can be handled by standard URL encoding.
set search to text returned of (display dialog "Enter song you wish to find" default answer "" buttons {"Search", "Cancel"} default button 1)
set search to stringReplace(search, space, "-")
do shell script "open 'http://www.mp3juices.com/search/'" & quoted form of search
on stringReplace(theText, searchString, replaceString)
set {oldTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, searchString}
set textItems to every text item of theText
set AppleScript's text item delimiters to replaceString
set newText to textItems as string
set AppleScript's text item delimiters to oldTID
return newText
end stringReplace
EDIT: updated the code, unlike the question mentioned that spaces are converted to underscores, mp3juice uses hyphens as substitution for whitespaces.
An update on this, despite the fact that the answer is 3 years old, as I faced the same problem: on recent versions of macOS/OS X/Mac OS X (I think, 10.10 or later), you can use ASOC, the AppleScript/Objective-C bridge:
use framework "Foundation"
urlEncode("my search string with [{?#äöü or whatever characters")
on urlEncode(input)
tell current application's NSString to set rawUrl to stringWithString_(input)
set theEncodedURL to rawUrl's stringByAddingPercentEscapesUsingEncoding:4 -- 4 is NSUTF8StringEncoding
return theEncodedURL as Unicode text
end urlEncode
It should be noted that stringByAddingPercentEscapesUsingEncoding is deprecated, but it will take some time until it’s removed from macOS.
URL encoding in AppleScript
For a general use case (for me at the moment to pass any ASCII url containing chars like #, &, ß, ö to the bit.ly API), I stumbled upon a nice code snippet that instantly added full support to my ShortURL clipboard pasting shortcut. Here's a quote from source:
i was looking for a quick and dirty way to encode some data to pass to a url via POST or GET with applescript and Internet Explorer, there were a few OSAXen which have that ability, but i didn't feel like installing anything, so i wrote this thing (works with standard ascii characters, characters above ascii 127 may run into character set issues see: applescript for converting macroman to windows-1252 encoding)
Notes
Double encoding should be duly noted.
Not tested on non-ASCII URLs.
Tested on OS X 10.8.5.
Code
on urlencode(theText)
set theTextEnc to ""
repeat with eachChar in characters of theText
set useChar to eachChar
set eachCharNum to ASCII number of eachChar
if eachCharNum = 32 then
set useChar to "+"
else if (eachCharNum ≠ 42) and (eachCharNum ≠ 95) and (eachCharNum < 45 or eachCharNum > 46) and (eachCharNum < 48 or eachCharNum > 57) and (eachCharNum < 65 or eachCharNum > 90) and (eachCharNum < 97 or eachCharNum > 122) then
set firstDig to round (eachCharNum / 16) rounding down
set secondDig to eachCharNum mod 16
if firstDig > 9 then
set aNum to firstDig + 55
set firstDig to ASCII character aNum
end if
if secondDig > 9 then
set aNum to secondDig + 55
set secondDig to ASCII character aNum
end if
set numHex to ("%" & (firstDig as string) & (secondDig as string)) as string
set useChar to numHex
end if
set theTextEnc to theTextEnc & useChar as string
end repeat
return theTextEnc
end urlencode
If you need to get the URL as a string (not just feed it into open which does a nifty job of encoding for you) and you're not above using a little Automator, you can throw some JavaScript into your AppleScript:
encodeURIComponent is a built in JavaScript function - it is a complete solution for encoding components of URIs.
For copy/pasters, here are all three scripts in the above Automator chain:
on run {input, parameters}
return text returned of (display dialog "Enter song you wish to find" default answer "" buttons {"Search", "Cancel"} default button 1)
end run
function run(input, parameters) {
return encodeURIComponent(input);
}
on run {input, parameters}
display dialog "http://www.mp3juices.com/search/" & input buttons {"okay!"} default button 1
end run
I was hunting around for URL encoding and decoding and came across this helpful link.
Which you can use like so:
set theurl to "https://twitter.com/zackshapiro?format=json"
do shell script "php -r 'echo urlencode(\"" & theurl & "\");'"
# gives me "https%3A%2F%2Ftwitter.com%2Fzackshapiro%3Fformat%3Djson"
set theurl to "https%3A%2F%2Ftwitter.com%2Fzackshapiro%3Fformat%3Djson"
return do shell script "php -r 'echo urldecode(\"" & theurl & "\");'"
# gives me "https://twitter.com/zackshapiro?format=json"
Or as functions:
on encode(str)
do shell script "php -r 'echo urlencode(\"" & str & "\");'"
end encode
on decode(str)
do shell script "php -r 'echo urldecode(\"" & str & "\");'"
end decode
Just so it's said, AppleScriptObjC allows us to use NSString to do the encoding. The script is complicated by the fact that different parts of the URL allow different characters (all of which I've added options for) but in most cases the 'query' option will be used.
See NSCharacterSet's dev page (the section called "Getting Character Sets for URL Encoding") for descriptions of the various URL parts.
use AppleScript version "2.4" -- Yosemite 10.10 or later
use framework "Foundation"
property NSString : class "NSString"
property NSCharacterSet : class "NSCharacterSet"
-- example usage
my percentEncode:"some text" ofType:"query"
on percentEncode:someText ofType:encodeType
set unencodedString to NSString's stringWithString:someText
set allowedCharSet to my charSetForEncodeType:encodeType
set encodedString to unencodedString's stringByAddingPercentEncodingWithAllowedCharacters:allowedCharSet
return encodedString as text
end percentEncode:ofType:
on charSetForEncodeType:encodeType
if encodeType is "path" then
return NSCharacterSet's URLPathAllowedCharacterSet()
else if encodeType is "query" then
return NSCharacterSet's URLQueryAllowedCharacterSet()
else if encodeType is "fragment" then
return NSCharacterSet's URLFragmentAllowedCharacterSet()
else if encodeType is "host" then
return NSCharacterSet's URLHostAllowedCharacterSet()
else if encodeType is "user" then
return NSCharacterSet's URLUserAllowedCharacterSet()
else if encodeType is "password" then
return NSCharacterSet's URLPasswordAllowedCharacterSet()
else
return missing value
end if
end charSetForEncodeType:
The Python Approach:
Find your python3 path (which python3) or if you don't have it, install using brew or miniconda
Now try this:
python_path = /path/to/python3
set search_query to "testy test"
tell application "Google Chrome"
set win to make new window
open location "https://www.google.com/search?q=" & url_encode(q)
end tell
on url_encode(input)
return (do shell script "echo " & input & " | " & python_path & " -c \"import urllib.parse, sys; print(urllib.parse.quote(sys.stdin.read()))\"
")
end url_encode
credits to #Murphy https://stackoverflow.com/a/56321886

Mavericks AppleScript count every desktop always returns 1

I've got a script taken from GitHub that is supposed to set the wallpaper of every desktop to a certain image depending on the time of day. (I have modified it from the original code to include more time ranges, issue shows in both versions)
The script attempts to count the number of desktops in order to change more than just the current desktop. It does this by first telling System Events the following
set theDesktops to a reference to every desktop
And then, in order to loop through every desktop, it does the following:
if ((count theDesktops) > 1) then
repeat with x from 2 to (count theDesktops)
--some code removed, see full code below
end repeat
end if
The issues is that count theDesktops always returns a 1, no matter how many desktops there are, as seen in the following screenshot.
http://ss.kobitate.com/2013-12-28_0922_2.png
What can be done to fix this? Here is the full code
(*
Script by Philip Hutchison, April 2013
http://pipwerks.com
MIT license http://pipwerks.mit-license.org/
This script assumes:
1. You have a folder named "Wallpapers" in your Pictures folder
2. You have a subfolder named "Time of Day" in Wallpapers
3. You have six subfolders inside "Time of Day", with names that match the variables below.
* If you decide to use different folder names, you must change the variables to match the new folder names
4. You have images inside each folder
For example:
/Users/YOUR_USER_NAME/Pictures/Wallpapers/Time of Day/Afternoon Early/image.jpg
GeekTool can execute this script for you at specified intervals. Use this line in the command field:
osascript ~/Pictures/Wallpapers/Time\ of\ Day/wallpaper.scpt
*)
-- BEGIN USER CONFIGURATION
-- supply folder names
set morningEarly to "Morning Early"
set morningLate to "Morning Late"
set afternoonEarly to "Afternoon Early"
set afternoonLate to "Afternoon Late"
set eveningEarly to "Evening Early"
set eveningLate to "Evening Late"
set nightEarly to "Night Early"
set nightLate to "Night Late"
-- for multiple monitor support.
-- set to true to display the same image on all desktops, false to show unique images on each desktop
set useSamePictureAcrossDisplays to true
-- END USER CONFIGURATION
-- get current hour
set h to hours of (current date)
-- set default periodOfDay
set periodOfDay to nightLate
-- change value of periodOfDay based on current time
if (h > 6 and h < 8) then
set periodOfDay to morningEarly
else if (h ≥ 8 and h < 10) then
set periodOfDay to morningLate
else if (h ≥ 10 and h < 12) then
set periodOfDay to afternoonEarly
else if (h ≥ 12 and h < 16) then
set periodOfDay to afternoonLate
else if (h ≥ 16 and h < 18) then
set periodOfDay to eveningEarly
else if (h ≥ 18 and h < 20) then
set periodOfDay to eveningLate
else if (h ≥ 20 and h < 22) then
set periodOfDay to nightEarly
else if (h ≥ 22) then
set periodOfDay to nightLate
end if
-- helper function ("handler") for getting random image
on getImage(folderName)
tell application "Finder"
return some file of folder ("Pictures:Wallpapers:Time of Day:" & folderName) of home as text
end tell
end getImage
tell application "Finder"
-- wrapped in a try block for error suppression
try
-- determine which picture to use for main display
set mainDisplayPicture to my getImage(periodOfDay)
-- set the picture for additional monitors, if applicable
tell application "System Events"
-- get a reference to all desktops
set theDesktops to a reference to every desktop
-- handle additional desktops
if ((count theDesktops) > 1) then
-- loop through all desktops (beginning with the second desktop)
repeat with x from 2 to (count theDesktops)
-- determine which image to use
if (useSamePictureAcrossDisplays is false) then
set secondaryDisplayPicture to my getImage(periodOfDay)
else
set secondaryDisplayPicture to my mainDisplayPicture
end if
-- apply image to desktop
set picture of item x of the theDesktops to secondaryDisplayPicture
end repeat
end if
end tell
-- set the primary monitor's picture
-- due to a Finder quirk, this has to be done AFTER setting the other displays
set desktop picture to mainDisplayPicture
end try
end tell
Edit: Fixed an unrelated mistake I found in the code
This seems to be fixed now. I remember testing this when #KobiTate posted it.
I am now on 10.9.1 but not sure when it was fixed
tell application "System Events"
set theDesktops to count of (a reference to every desktop)
set theDesktops2 to count every desktop
end tell
log "count of (a reference to every desktop) = " & theDesktops
log "count every desktop = " & theDesktops2
Returns:
(count of (a reference to every desktop) = 2)
(count every desktop = 2)

Cannot pass handler parameter to code. Newbie

Background: I am trying to pass caller information from a telephony application (Phone Amego) to my Samsung tv using its AllShare feature. In order to do so I have to send a soap message with the caller information. Phone Amego provides an easy way to assign an applescript to call events. But, I have no programming experience whatsoever!
Sofar I have succeeded in making a script which reads a soap message, updates the required fields and sends it to my tv. Perfect, at least the result, the code may not be perfect but it works. Here is the code.
set callerID_string to "John Doe : 1-917-123-4567"
set AppleScript's text item delimiters to {":"}
set pieces to text items of callerID_string
set callerID_name to item 1 of pieces
set callerID_number to item 2 of pieces
set AppleScript's text item delimiters to {""}
set myDate to do shell script "date '+%d.%m.%Y'"
set myTime to do shell script "date '+%T'"
set total_Length to (length of callerID_name) + (length of callerID_number) + 780
set search_strings to {"Content-Length: 796", "2013-01-01", "00:00:00", "Mike", "777-777-7777"}
set replace_strings to {"Content-Length:" & total_Length, myDate, myTime, callerID_name, callerID_number}
tell application "Finder"
set theFile to alias "Macintosh HD:Users:Marc:Desktop:IncCallMBsTemplate.txt"
open for access theFile
set fileRef to open for access (theFile as alias)
set fileContents to (read fileRef)
close access theFile
end tell
set the clipboard to fileContents
repeat with i from 1 to (count search_strings)
set the_string to the clipboard
set the_string to my snr(the_string, item i of search_strings, item i of replace_strings)
end repeat
on snr(the_string, search_string, replace_string)
tell (a reference to my text item delimiters)
set {old_atid, contents} to {contents, search_string}
set {the_string, contents} to {the_string's text items, replace_string}
set {the_string, contents} to {"" & the_string, old_atid}
end tell
set the clipboard to the_string
-- Create a file handler for the file to write to.
set myFile to (open for access alias "Macintosh HD:Users:Marc:Desktop:Test.txt" with write permission)
try
-- Delete current contents of the file
set eof myFile to 0
-- Write to file
write the_string to myFile as «class utf8»
end try
-- Close the file
close access myFile
end snr
set cmd to "/Usr/bin/nc 10.0.1.7 52235 < /Users/Marc/Desktop/Test.txt"
do shell script cmd
Problem: In the script above I have set a value to the variable callerID_string, but I should obtain it from Phone Amego through the handler call_from(callerID_string). But whatever I try, I cannot pass that callerID_string to my code. It consists of 2 parts namely the caller's name and number. The code should start like:
on call_from(callerID_string)
Any help would be highly appreciated.
I assume your script is running with the other app at the same time and it needs that handler and therefore a little re-designing so we can call the (former main) code as a subroutine.
I'm not sure if I understood the situation correctly but here it is anyway:
I added the on call_from... handler which calls the rest of the code as subroutine (myAction).
First commented line in code can be uncommented and used to test-run it with AppleScript Editor. Remove the line when not needed anymore.
testFilePath is a property and globally visible. Also, I changed the hardcoded file-path-stuff so it finds the path to the desktop.
property testFilePath : ""
-- my myAction("John Doe : 1-917-123-4567")
on call_from(callerID_string)
my myAction(callerID_string)
end call_from
on myAction(CIS)
if CIS is "" then
tell me to activate
display dialog "Caller ID is empty." buttons {"Quit"} default button 1 with icon 0
return
end if
set pathToDesktop to (path to desktop) as text
set testFilePath to pathToDesktop & "Test.txt"
set callerID_string to CIS -- "John Doe : 1-917-123-4567"
set lastTextItemDelimeter to AppleScript's text item delimiters
set AppleScript's text item delimiters to {" : "}
set pieces to text items of callerID_string
set callerID_name to item 1 of pieces
set callerID_number to item 2 of pieces
set AppleScript's text item delimiters to {""} -- or lastTextItemDelimeter if you want to change it back to last
set myDate to do shell script "date '+%d.%m.%Y'"
set myTime to do shell script "date '+%T'"
set total_Length to (length of callerID_name) + (length of callerID_number) + 780
set search_strings to {"Content-Length: 796", "2013-01-01", "00:00:00", "Mike", "777-777-7777"}
set replace_strings to {"Content-Length:" & total_Length, myDate, myTime, callerID_name, callerID_number}
set templateFile to pathToDesktop & "IncCallMBsTemplate.txt"
tell application "Finder"
set theFile to templateFile as alias -- Macintosh HD:Users:Marc:Desktop:IncCallMBsTemplate.txt"
open for access theFile
set fileRef to open for access (theFile as alias)
set fileContents to (read fileRef)
close access theFile
end tell
set the clipboard to fileContents
repeat with i from 1 to (count search_strings)
set the_string to the clipboard
set the_string to my snr(the_string, item i of search_strings, item i of replace_strings)
end repeat
set cmd to "/usr/bin/nc 10.0.1.7 52235 < " & quoted form of (POSIX path of testFilePath)
do shell script cmd
end myAction
on snr(the_string, search_string, replace_string)
tell (a reference to my text item delimiters)
set {old_atid, contents} to {contents, search_string}
set {the_string, contents} to {the_string's text items, replace_string}
set {the_string, contents} to {"" & the_string, old_atid}
end tell
set the clipboard to the_string
-- Create a file handler for the file to write to.
set myFile to (open for access (testFilePath as alias) with write permission)
try
-- Delete current contents of the file
set eof myFile to 0
-- Write to file
write the_string to myFile as «class utf8»
on error the error_message number the error_number
-- display dialog "Error: " & the error_number & ". " & the error_message buttons {"Cancel"} default button 1
log "Error: " & the error_number & ". " & the error_message
end try
-- Close the file
close access myFile
end snr

Loop Over Video Files in Folder to get video length

I have the following which returns how many seconds a selected video file is.
However I was after a way to just give it the movie folder and for it to then loop through all subdirectories and find all video file types.
Once it has these I would like to list the video length in "1 hour 53 seconds" type format as "7990 seconds" isn't too helpful.
Thanks
set macPath to (choose file) as text
tell application "System Events"
set ts to time scale of movie file macPath
set dur to duration of movie file macPath
set movieTime to dur / ts
end tell
You have several sub-questions involved in your question.
1) How do I get all of the files in a folder, including the sub folders
2) how do I filter that list to only include video files
3) How do I loop through that list of video files and extract information from each and
4) How do I convert seconds into a useable string of words
Normally I would ask that you break it down into those individual questions because it's a large task for someone to write the whole thing for you. However, in this case you're lucky because I had done this before myself... so you can have my script. I put lots of comments in the code to help you learn how it works.
-- I found these extensions for video files here http://www.fileinfo.net/filetypes/video
-- we can check the file extensions of a file against this list to evaluate if it's a video file
set video_ext_list to {"3g2", "3gp", "3gp2", "3gpp", "3mm", "60d", "aep", "ajp", "amv", "asf", "asx", "avb", "avi", "avs", "bik", "bix", "box", "byu", "cvc", "dce", "dif", "dir", "divx", "dv", "dvr-ms", "dxr", "eye", "fcp", "flc", "fli", "flv", "flx", "gl", "grasp", "gvi", "gvp", "ifo", "imovieproject", "ivf", "ivs", "izz", "izzy", "lsf", "lsx", "m1v", "m2v", "m4e", "m4u", "m4v", "mjp", "mkv", "moov", "mov", "movie", "mp4", "mpe", "mpeg", "mpg", "mpv2", "msh", "mswmm", "mvb", "mvc", "nvc", "ogm", "omf", "prproj", "prx", "qt", "qtch", "rm", "rmvb", "rp", "rts", "sbk", "scm", "smil", "smv", "spl", "srt", "ssm", "svi", "swf", "swi", "tivo", "ts", "vdo", "vf", "vfw", "vid", "viewlet", "viv", "vivo", "vob", "vro", "wm", "wmd", "wmv", "wmx", "wvx", "yuv"}
-- get the folder to check
set f to choose folder
-- notice the use of "entire contents" to also go through subfolders of f
-- use a "whose" filter to find only the video files
tell application "Finder"
set vidFiles to (files of entire contents of f whose name extension is in video_ext_list) as alias list
end tell
-- use a repeat loop to loop over a list of something
set vidList to {} -- this is where we store the information as we loop over the files
repeat with aFile in vidFiles
-- get some information from aFile
tell application "System Events"
set vidFile to movie file (aFile as text)
set ts to time scale of vidFile
set dur to duration of vidFile
end tell
-- add the information to the "storage" list we made earlier
set end of vidList to {POSIX path of aFile, secs_to_hms(dur / ts)}
end repeat
return vidList
(*=================== SUBROUTINES ===================*)
-- convert seconds into a string of words
-- the use of "mod" and "div" here makes it easy
-- we also make sure that each value is at least 2 places long to make it look nicer
on secs_to_hms(the_secs)
set timeString to ""
set hr to the_secs div hours
if hr is not 0 then set timeString to timeString & (text -2 thru -1 of ("0" & (hr as text))) & " hours "
set min to the_secs mod hours div minutes
if min is not 0 then set timeString to timeString & (text -2 thru -1 of ("0" & (min as text))) & " minutes "
set sec to the_secs mod minutes div 1
if sec is not 0 then
set fraction to text 2 thru 3 of ((100 + the_secs mod 1 * 100) as text)
set timeString to timeString & (sec as text) & "." & fraction & " seconds"
end if
if timeString ends with space then set timeString to text 1 thru -2 of timeString
return timeString
end secs_to_hms
I came across this post because I wanted to have a log of video files in a folder; something I could import in a spreadsheet, also to calculate the total duration but not only.
The posted script didn't work for me so I ended up importing the folder in Final Cut Pro, doing Batch Export on the folder and than File > Export > Batch List, which resulted in a plain text file I could import in a spreadsheet as the start of a log and to calculate the total duration.
Perhaps this helps others.

Resources