How does one convert a QuickTime duration in frames to a time format using AppleScript? - applescript

I'm relatively new to AppleScript. I'm trying to convert a QuickTime duration to a mm:ss time format that rounds to the nearest second. Currently, it comes up as minutes and decimal places that I want to convert to seconds.
I much appreciate any suggestions.
Here's what I have, so far…
set these_items to choose file with prompt "Select source file(s)" with multiple selections allowed
repeat with oneItem in these_items
tell application "System Events"
try
set q to QuickTime file (oneItem as text)
set MovieDuration to ((duration of contents of q) / (time scale of contents of q)) / 60
display dialog "Movie duration of " & name of q & " = " & MovieDuration
end try
end tell
end repeat

I think I've figured it out. This seems to give me the result I want, anyway:
set these_items to choose file with prompt "Select source file(s)" with multiple selections allowed
repeat with oneItem in these_items
tell application "System Events"
try
set q to QuickTime file (oneItem as text)
set MovieSeconds to (((duration of contents of q) / (time scale of contents of q)) mod 60) as string
set x to text 1 thru ((offset of "." in MovieSeconds) - 1) of MovieSeconds
set MovieSeconds to text -2 thru -1 of ("00" & x)
set MovieMinutes to ((duration of contents of q) / (time scale of contents of q)) div 60
display dialog "Movie duration of " & name of q & " = " & MovieMinutes & ":" & MovieSeconds
end try
end tell
end repeat

Another way to get the timestamp duration is to give the movie a date with a midnight time and then add the duration seconds to it, and then ask for the “time string” of that date. The time string is formatted HH:MM:SS.
This example works with QuickTime Player 10.3 on Mavericks:
tell application "QuickTime Player"
activate
open (choose file with prompt "Choose a movie file:")
set theMovie to a reference to the front document
set theMovieDurationSeconds to the duration of theMovie
set theMovieDate to date "Saturday, January 1, 2000 at 00:00:00"
set theMovieDate to theMovieDate + theMovieDurationSeconds
set theMovieDurationTimeString to the time string of theMovieDate
display dialog "The movie duration:" & space & theMovieDurationTimeString buttons {"Cancel", "OK"} default button "OK" with title (the name as text) with icon note giving up after 60
end tell
The time string will be “00:08:20” for a movie with a duration of 500 seconds.
The advantage of this method is you don’t have to do any math, and it should work with movies that are up to 23:59:59 in duration.
Also notice that you can just ask QuickTime Player for the movie duration.

Related

How to get Apple music artwork using AppleScript

I have an AppleScript which retrieves several properties of the current track playing on apple music but I can't retrieve the artwork
if application "Music" is running then
tell application "Music"
if player state is playing or player state is paused then
set currentTrack to current track
return {get player state} & {get artist of currentTrack} & {get name of currentTrack} & {get album of currentTrack} & {get kind of currentTrack} & {get duration of currentTrack} & {player position} & {get genre of current track} & {get id of current track}
else
return "stopped"
end if
end tell
else
return "stopped"
end if
This is very simple i just couldn't find it, so Doug made a very simple script that you can find here and that i reworked a bit it save the current track artwork to the same location as the script and name it tmp.jpg or png
tell application "Music"
try
if player state is not stopped then
set alb to (get album of current track)
tell artwork 1 of current track
if format is JPEG picture then
set imgFormat to ".jpg"
else
set imgFormat to ".png"
end if
end tell
set rawData to (get raw data of artwork 1 of current track)
else
return
end if
on error
display dialog "Problem getting track info." buttons {"OK"}
return
end try
end tell
--get current path
tell application "Finder"
set current_path to container of (path to me) as alias
end tell
--create path to save image as jpg or png
set newPath to ((current_path as text) & "tmp" & imgFormat) as text
try
--create file
tell me to set fileRef to (open for access newPath with write permission)
--overwrite existing file
write rawData to fileRef starting at 0
tell me to close access fileRef
on error m number n
log n
log m
try
tell me to close access fileRef
end try
end try

macOS Photos and AppleScript: Quicker organization method

The Goal:
In macOS Photos App, highlight/select a bulk of photos, iterate each one.
AppleScript will tell Photos to quickview the photo, ask what 'Album(s)' to add the photo to, then it will ask for a title and caption.
I'm doing this because the 'Info' panel that provides this function doesn't allow for rapid entry, and it's pretty small to work with.
So I suppose I need a couple things:
Show the picture (tell Photos to quick look it)
Identify the 'My Album' folders (eliminate the smart folders from the mix)
Prompt and Update the Title and the Caption (called name and description in the def)
Add the photo to the selected Albums.
I'm not sure if it's just me, but the AppleScript scripting on Photos is just not something I can wrap my head around very well.
Here's what I have so far, but I was hoping you can help.
tell application "Photos"
--Find All Albums
set thefullList to the name of every album of every folder
-- Need:Figure out how to strip Smart Albums out of this query
-- Set comma as the delim to separate the folders/albums
set oldDelimiters to AppleScript's text item delimiters
set AppleScript's text item delimiters to ","
set thefullList to every item of thefullList
set AppleScript's text item delimiters to oldDelimiters
-- Test the output (fails to delim, and won't display the string)
display dialog thefullList
-- Clean list of Albums
set albumNames to {thefullList}
-- Get the selected photos from Photos
set theSelection to (get selection)
-- Iterate through each photo
repeat with i in theSelection
-- Tell Photos to 'quick look'
-- Need:(no idea how to make that work yet)
-- Ask the user to choose the Album(s) this photo should go into
set theAlbumChoice to choose from list albumNames with prompt "Where should this photo go?"
-- Tell the Album that this photo is now added
set theAlbum to theAlbumChoice
add i to theAlbum
-- Ask for Title and Caption
display dialog "What's the Title of this Photo?"
set theTitle to text returned of result
display dialog "What's the Caption of this Photo?"
set theCaption to text returned of result
-- Get the Photo ID for adding MetaData
set selectionID to id of item i of theSelection
-- Set the Title and caption
set name of media item id selectionID to theTitle
set description of media item id selectionID to theCaption
end repeat
end tell
property albumNames : {}
property albumIDs : {}
tell application "Photos"
activate
my getAlbumNames(it) -- get all album names and IDs (recursively)
repeat with aPhoto in (get selection) -- process each selected photo
try -- Get the Photo ID
set selectionID to id of aPhoto
on error errorMessage
set ATID to AppleScript's text item delimiters
set AppleScript's text item delimiters to "\""
set selectionID to text item 2 of errorMessage
set AppleScript's text item delimiters to ATID
end try
spotlight media item id selectionID -- Tell Photos to 'quick look'
-- Ask the user to choose the Album(s) this photo should go into
set theAlbumChoice to choose from list albumNames with prompt "Where should this photo go?"
if theAlbumChoice is false then return
-- Find destination folder's ID and add photo to it
repeat with k from 1 to count albumNames
if (item 1 of theAlbumChoice) is (item k of albumNames) then
set theAlbumID to item k of albumIDs
exit repeat
end if
end repeat
add {media item id selectionID} to album id theAlbumID
-- Ask for Title and Caption, and set them
display dialog "What's the Title of this Photo?" default answer ""
set theTitle to text returned of result
display dialog "What's the Caption of this Photo?" default answer ""
set theCaption to text returned of result
set name of media item id selectionID to theTitle
set description of media item id selectionID to theCaption
end repeat
end tell
on getAlbumNames(aFolder) -- recursive handler
tell application "Photos"
set albumNames to albumNames & name of albums of aFolder
set albumIDs to albumIDs & id of albums of aFolder
repeat with subFolder in (get folders of aFolder)
my getAlbumNames(subFolder)
end repeat
end tell
end getAlbumNames

Splitting full-screen apps with AppleScript

I have been using this script in Automator, which toggles apps between full-screen and windowed mode. I am a frequent user of split-screen applications (introduced in El Capitan), so is there any way to modify this script to enable split-screen? I know there's no keyboard shortcut for splitting, so this is definitely a shot in the dark.
I managed to cobble something together, working off an AppleScript/python thing that I found in this MacScripter post. It does the following:
Pulls a list of open application windows from System Events, and allows the user to select one or two (for full screen or split screen)
Launches "Mission Control"
GUI-scripts the Dock to find references to the various window-buttons and spaces in Mission Control that we need to access
Programmatically drags the buttons around to create a new fullscreen or splitscreen space
Clicks on the newly created space to activate it
You might be able to trim some time down on all the half-second delays, but Mission Control is expecting human interaction and handles things lazily. It will miss GUI requests that come too fast.
(* collect names of open app windows *)
tell application "System Events"
set windowNames to {}
set theVisibleProcesses to every process whose visible is true
repeat with thisProcess in theVisibleProcesses
set windowNames to windowNames & (name of every window of thisProcess whose role description is "standard window")
end repeat
end tell
(* choose 1 name for fullscreen, two names for split screen *)
set selectedItems to choose from list windowNames with title "Split It" with prompt "Choose items to add to split view." with multiple selections allowed without empty selection allowed
if selectedItems is false or (count of selectedItems) > 2 then return
set selectedWindow1 to item 1 of selectedItems
if (count of selectedItems) = 2 then
set selectedWindow2 to item 2 of selectedItems
end if
tell application "Mission Control"
launch
end tell
(*
The dock has a set of nested UI elements for Mission Control, with the following structure:
"Mission Control"'s group 1 (the base container)
group 1, group 2, .... (groups for each desktop)
buttons for open windows on each desktop
group "Spaces Bar"
a single button (the '+' buttan to add a new space)
a list
buttons for the desktops and any already-made spaces
*)
tell application "System Events"
tell process "Dock"'s group "Mission Control"'s group 1
tell group "Spaces Bar"'s list 1
set {p, s} to {position, size} of last UI element
set XTarget to (item 1 of p) + (item 1 of s) + 100
set YTarget to (item 2 of p) + (item 2 of s) + 100
end tell
tell group 1
set viewButton1 to button selectedWindow1
set {x, y} to get viewButton1's position
my mouseDrag(x, y, XTarget, YTarget, 0.5)
end tell
tell group "Spaces Bar"'s list 1
set {p, s} to {position, size} of last UI element
set XTarget to (item 1 of p) + (item 1 of s) + 10
set YTarget to (item 2 of p) + (item 2 of s) + 10
end tell
try
tell group 1
set viewButton2 to button selectedWindow2
set {x, y} to get viewButton2's position
my mouseDrag(x, y, XTarget, YTarget, 0.5)
end tell
end try
tell group "Spaces Bar"'s list 1
delay 0.5
set lastUI to last UI element
click lastUI
end tell
end tell
end tell
on mouseDrag(xDown, yDown, xUp, yUp, delayTime)
do shell script "
/usr/bin/python <<END
from Quartz.CoreGraphics import CGEventCreateMouseEvent
from Quartz.CoreGraphics import CGEventCreate
from Quartz.CoreGraphics import CGEventPost
from Quartz.CoreGraphics import kCGEventLeftMouseDown
from Quartz.CoreGraphics import kCGEventLeftMouseUp
from Quartz.CoreGraphics import kCGMouseButtonLeft
from Quartz.CoreGraphics import kCGHIDEventTap
from Quartz.CoreGraphics import kCGEventLeftMouseDragged
from Quartz.CoreGraphics import kCGEventMouseMoved
import time
def mouseEvent(type, posx, posy):
theEvent = CGEventCreateMouseEvent(None, type, (posx,posy), kCGMouseButtonLeft)
CGEventPost(kCGHIDEventTap, theEvent)
def mousemove(posx,posy):
mouseEvent(kCGEventMouseMoved, posx,posy);
def mousedrag(posx,posy):
mouseEvent(kCGEventLeftMouseDragged, posx, posy);
def mousedown(posxdown,posydown):
mouseEvent(kCGEventLeftMouseDown, posxdown,posydown);
def mouseup(posxup,posyup):
mouseEvent(kCGEventLeftMouseUp, posxup,posyup);
ourEvent = CGEventCreate(None);
mousemove(" & xDown & "," & yDown & ");
mousedown(" & xDown & "," & yDown & ");
time.sleep(" & (delayTime as text) & ");
mousedrag(" & xUp & "," & yUp & ");
time.sleep(" & (delayTime as text) & ");
mouseup(" & xUp & "," & yUp & ");
END"
end mouseDrag
I agree with Ted Wrigley's answer above, but I would make the following changes:
(...)
tell application "System Events"
tell process "Dock"'s group "Mission Control"'s group 1
tell group "Spaces Bar"'s list 1
set countSpaces to count of UI elements
set {p, s} to {position, size} of last UI element
set XTarget to (item 1 of p) + (item 1 of s) + (100 * countSpaces)
set YTarget to (item 2 of p) + (item 2 of s) + 100
end tell
(...)
If you want to run this script multiple times, you need to count the number of open Spaces to correctly find the right spot to drag the window to. Otherwise, the windows are always are always dragged to the 2nd position of the Spaces Bar.

Set a camera in quicktime using applescript

I know there is probably a very simple answer to this. I'm trying to setup an Applescript application that when activated will launch quicktime, open a new movie recording, set the camera and audio, start the recording and then end the recording and save it after 30 seconds.
I currently have a script that is doing everything except setting the camera and audio source. Any tips on how to select a certain camera and audio source using applescript?
Thanks!
Here is the code as it stands now..
--Set some Variables
--Max length of recording
set maxrec to 20 --in seconds
--Ending Message
set EndMsg to "Thank you for participating in this project. Your video has been recorded."
--Begin Loop
repeat
--Get the person's name
repeat
display dialog "What's your name?" default answer ""
set theName to (text returned of result)
if theName ≠ "" then exit repeat
end repeat
--Set the date
set theDate to current date
set y to text -4 thru -1 of ("0000" & (year of theDate))
set m to text -2 thru -1 of ("00" & ((month of theDate) as integer))
set d to text -2 thru -1 of ("00" & (day of theDate))
set h to text -2 thru -1 of ("00" & (hours of theDate))
set mm to text -2 thru -1 of ("00" & (minutes of theDate))
set dateStamp to (y & "-" & m & "-" & d & " " & h & mm as string)
--Create a folder for the person
tell application "Finder"
set p to path to movies folder from user domain
try
make new folder at p with properties {name:"Video Clips"}
end try
set p to (path to movies folder from user domain as text) & "Video Clips:"
make new folder at p with properties {name:dateStamp & " " & theName}
set thePath to result
--Establish the final name of the movie
set fileName to ((thePath as text) & dateStamp & ".mov" as string)
end tell
--Open New Recording, start and stop it
tell application "QuickTime Player"
set newMovieRecording to new movie recording
set windowID to id of first window whose name = "Movie Recording"
delay 2
tell newMovieRecording
--Set Camera to Blackmagic
set current camera of newMovieRecording to Blackmagic of video recording devices
start
end tell
set theSeconds to maxrec
repeat theSeconds times
display dialog theSeconds buttons {} giving up after 1 with title "REMAINING TIME"
set theSeconds to (theSeconds - 1)
end repeat
tell newMovieRecording
stop
end tell
--save and close the recording
set newMovieRecordingDoc to first document whose name = (get name of first window whose id = windowID)
tell newMovieRecordingDoc to save in fileName
set SavedRecordingDoc to first document whose name = (get name of first window whose id = windowID)
tell SavedRecordingDoc to close
quit
end tell
--Display "Thank You" Message
tell application "System Events" to set frontmost of process "Video Booth" to true
display dialog EndMsg giving up after 20 buttons {"Continue…"} ¬
default button 1
end repeat
Here is the error I get right now when I run it.
error "QuickTime Player got an error: Can’t make Blackmagic of every video recording device of document \"Movie Recording\" into type specifier." number -1700 from Blackmagic of every video recording device of document "Movie Recording" to specifier
use the current camera and current microphone properties of your movie recording object. Just replace item 1 with the appropriate device:
set current camera of recording to item 1 of video recording devices
set current microphone of recording to item 1 of audio recording devices
I had accomplished this by doing it manually
tell application "System Events" to tell process "QuickTime Player"
#To open dialog to show available cameras
click button 3 of window 1
#To select our device
click menu item "your_camera_name" of menu 1 of button 3 of window 1
end tell
With this the dialog will open and you will select your camera from the list...
Taken from another answer I made:
https://stackoverflow.com/a/45454785/3685973

I want to set variable once in an applescript droplet but it makes me set it for every file

I wrote an applescript droplet where I would like to:
drag one or more images onto the droplet
3 display dialogs appear asking 'width', 'height', 'format'
process all dropped images using the above text returned of the
3 display dialogs
Currently, the 3 display dialogs appear for each image (e.g. 3 images = 9 dialogs appear). Is there a way I can only answer these dialogs once? Here's my script:
on run
display dialog "This is a droplet"
end run
on open draggedItems
set tid to AppleScript's text item delimiters
--ask for new width
set newWidth to text returned of (display dialog "New Width" default answer ¬
"45" buttons {"Continue…", "Cancel"} ¬
default button 1)
--ask for new height
set newHeight to text returned of (display dialog "New Height" default answer ¬
"45" buttons {"Continue…", "Cancel"} ¬
default button 1)
--ask for formatType
set newFormat to text returned of (display dialog "Image Format" default answer ¬
"jpg" buttons {"Continue…", "Cancel"} ¬
default button 1)
--repeat
repeat with i in draggedItems
set theFile to (i as alias)
set theFilePath to (the POSIX path of theFile)
set fullFileName to name of (info for theFile without size)
set AppleScript's text item delimiters to "."
set fileNameNoExtension to first text item of fullFileName
--set fileExtension to second text item of fullFileName
set AppleScript's text item delimiters to tid
do shell script ("/usr/local/bin/convert " & quoted form of theFilePath & " -resize " & newWidth & "x" & newHeight & "\\! ~/desktop/" & fileNameNoExtension & "." & newFormat)
end repeat
end open
on open draggedItems is already an repeat loop, if you drop 4 files on this droplet
on open draggedItems
display dialog (draggedItems as text)
end open
you will get 4 different dialogs.
You could do something like this
property askingForNew : true
on open draggedItems
if askingForNew is true then
--display dialogs
set askingForNew to false
end if
display dialog (draggedItems as text)
end open
or drag the folder on the droplet and go through the files of it (like this).

Resources