Play custom bundled sound in apple script - macos

So im trying to use shellscript "afplay " in applescript to play an .m4a file I bundled into the app resource. Not entirely sure how it works.
Got this after a bit of searching around,
set soundPath to POSIX path of (path to resource "Sound File.aiff")
do shell script "afplay " & quoted form of soundPath
This isnt really what I want.

playAudio() -- place this Line To call the handler to Play An Audio File.
on playAudio()
set audioFile to path to resource "Sound File.aiff"
set theFile to POSIX path of audioFile
do shell script "afplay -q 1 -t 25 " & " " & quoted form of theFile
end playAudio
-- Command Line OPTIONS For Playing Audio Files
(*
afplay [option...] audio_file
Options: (may appear before or after arguments)
{-v | --volume} VOLUME
set the volume for playback of the file
{-h | --help}
print help
{ --leaks}
run leaks analysis
{-t | --time} TIME
play for TIME seconds
{-r | --rate} RATE
play at playback rate
{-q | --rQuality} QUALITY
set the quality used for rate-scaled playback (default is 0 - low quality, 1 - high quality)
{-d | --debug}
debug print output
*)

Related

Changing MacOS Location based on SSID - check current location before changing

In this thread I received some assistance with getting this script to work correctly. The script essentially sets my network location according to the SSID I'm connected to. This is now working, however, it generates a lot of nuisance notifications.
Every time my laptop joins a wifi network, the script runs, sets the network location, and gives me a notification. Since power nap periodically joins the wifi to check for emails/updates and what have you, after a long weekend I'll get dozens of identical notifications.
How can I modify the script so that it only send a notification if the network location is changed to something different, not just when the script runs? Can I somehow check the existing network location and only change it/trigger a notification if the "new" location is different to the "existing" location?
Again, I'm extremely new to scripting on mac and GitHub in general; my previous experience is all on Windows and largely self taught.
Script:
#!/bin/bash
# automatically change configuration of Mac OS X based on location
# redirect all IO to a logfile
mkdir -p /usr/local/var/log
exec &>/usr/local/var/log/locationchanger.log
# get a little breather before we get data for things to settle down
sleep 2
# get SSID
SSID=$(/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -I | sed -n 's/^ *SSID: //p')
echo $(date) "New SSID found: $SSID"
# LOCATIONS
LOCATION=
Location_Automatic="Automatic"
Location_Office="Office"
Location_Site="Site"
# SSIDS
SSID_Office="My Office SSID"
SSID_Site="My Mobile SSID"
# SSID -> LOCATION mapping
case $SSID in
"$SSID_Office") LOCATION="$Location_Office";;
"$SSID_Site" ) LOCATION="$Location_Site";;
esac
REASON="SSID changed to $SSID"
# Location_Automatic
if [ -z "$LOCATION" ]; then
LOCATION="$Location_Automatic"
REASON="Automatic Fallback"
fi
# change network location
scselect "$LOCATION"
case $LOCATION in
"$Location_Automatic" )
osascript -e 'display notification "Network Location Changed to Automatic" with title "Network Location Changed"'
;;
"$Location_Office" )
osascript -e 'display notification "Network Location Changed to Office" with title "Network Location Changed"'
;;
"$Location_Site" )
osascript -e 'display notification "Network Location Changed to Site" with title "Network Location Changed"'
;;
esac
echo "--> Location Changer: $LOCATION - $REASON"
exit 0
This thread explains how to get the current network location.
I added the following code to get the current network location before making any changes:
CurrLoc=$(scselect | awk '{if ($1=="*") print $3}' | sed 's/[()]//g')
And then a simple if statement to exit the script early if the evaluated "new" network location matched the existing one:
if [ "$CurrLoc" = "$LOCATION" ]
then
exit 0
fi
# existing code to change network location and show notifications

Progress Bar in Applescript window

I want to download different apps with a bash script on macOS.
As there are some larger downloads (e.g. Office 365) I would like to include a progress bar in a regular macOS Window.
The applications download+install script looks like this
cd ~/Downloads/ && { curl -O https://dl.google.com/chrome/mac/stable/GGRO/googlechrome.dmg ; cd -; }
sudo hdiutil attach ~/Downloads/googlechrome.dmg
sudo cp -r /Volumes/Google\ Chrome/Google\ Chrome.app /Applications/
diskutil unmount Google\ Chrome
But this does not show any progress for the user (script will run in background).
I found the following example and edited it a bit to my likings
chromedl() {
osascript <<AppleScript
set progress description to "Loading"
set progress additional description to "Please wait"
set progress total steps to 3
repeat with i from 1 to 4
set theSourceCode to do shell script "curl -L -m 30 seconds [url=https://dl.google.com/chrome/mac/stable/GGRO/googlechrome.dmg]https://dl.google.com/chrome/mac/stable/GGRO/googlechrome.dmg]"
set progress completed steps to i
end repeat
display dialog "Progress bar is complete."
AppleScript
But this creates a curl execution error.
Please help me with a functioning Curl Download + Progress Bar script
A basic progress spinner window is easy enough to create using AppleScriptObjectiveC. Copy the following into Script Editor and run it in the foreground (command-control-R, or use the menu command Script→Run in Foreground, which appears when you hold down the control key).
use framework "AppKit"
use AppleScript version "2.4" -- Yosemite 10.10 or later required
use scripting additions
-- convenience properties to make ASOC more readable
property ca : current application
property NSPanel : class "NSPanel"
property NSView : class "NSView"
property NSProgressIndicator : class "NSProgressIndicator"
property NSTextField : class "NSTextField"
property HUD_mask : 8192
property nonactivating_mask : 128
global progress_panel, progress_indicator, label_field
make_progress_panel()
progress_indicator's startAnimation:me
progress_panel's orderFront:me
-- just hang it out there for 5 seconds as proof of concept
delay 5
progress_panel's |close|()
on make_progress_panel()
-- make floating panel
set content_rect to ca's NSMakeRect(200, 800, 140, 80)
set progress_panel to NSPanel's alloc's initWithContentRect:content_rect styleMask:(HUD_mask + nonactivating_mask) backing:(ca's NSBackingStoreBuffered) defer:true
set progress_panel's floatingPanel to true
-- make progress indicator
set progress_rect to ca's NSMakeRect(0, 0, 40, 40)
set progress_indicator to NSProgressIndicator's alloc's initWithFrame:progress_rect
set progress_indicator's indeterminate to true
set progress_indicator's |style| to 1
set progress_indicator's translatesAutoresizingMaskIntoConstraints to false
--make text field
set label_field to NSTextField's labelWithString:"Downloading"
set label_field's translatesAutoresizingMaskIntoConstraints to false
-- make container view, and add subviews
set content_view to NSView's alloc's initWithFrame:content_rect
content_view's addSubview:label_field
content_view's addSubview:progress_indicator
progress_indicator's sizeToFit()
set progress_panel's contentView to content_view
-- view constraints, for alignment
set pi_y_centering to progress_indicator's centerYAnchor's constraintEqualToAnchor:(content_view's centerYAnchor)
set lf_y_centering to label_field's centerYAnchor's constraintEqualToAnchor:(content_view's centerYAnchor)
pi_y_centering's setActive:true
lf_y_centering's setActive:true
set lf_left_margin to content_view's leadingAnchor's constraintEqualToAnchor:(label_field's leadingAnchor) |constant|:-10
lf_left_margin's setActive:true
set pi_left_margin to label_field's trailingAnchor's constraintEqualToAnchor:(progress_indicator's leadingAnchor) |constant|:-10
pi_left_margin's setActive:true
set pi_right_margin to progress_indicator's trailingAnchor's constraintGreaterThanOrEqualToAnchor:(content_view's trailingAnchor) |constant|:10
pi_left_margin's setActive:true
end make_progress_panel
The simplest way to make this work with curl, I think, is to detach the curl process entirely and recover its pid, like so (the code at the end detaches the process and sends the output to oblivion, then returns the pid):
set curl_pid to do shell script "curl -L [url=...] &> /dev/null & echo $!"
Once you have the pid you can set up a loop (or an idle handler, if you create an app) and periodically check to see if the process is still active:
try
set b to do shell script "pgrep curl | grep " & curl_pid
on error
progress_indicator's stopAnimation:me
progress_panel's |close|()
end try
If you want a determinate progress bar, that's easy enough to manage, but you have to figure out a way to measure progress. This link suggests you can get the headers for a file first and extract the file size; you could compare that against the actual on-disk file size as the download progresses, and feed the ratio into the progress bar.

How to save WAV file with script in praat?

I try to save a praat sound object to wav file. There is no problem when I do it in GUI. But it complains "Sounds not concatenated and not saved" in script. Does anyone know why?
Here is the command line output:
~/Downloads$ /Applications/Praat.app/Contents/MacOS/Praat --run aa1.praat
Error: Cannot create file “/Users/hgneng/Downloads/"/Users/hgneng/Downloads/aa2.wav"”.
Sounds not concatenated and not saved to “/Users/hgneng/Downloads/"/Users/hgneng/Downloads/aa2.wav"”.
Script line 15 not performed or completed:
« Save as WAV file... "/Users/hgneng/Downloads/aa2.wav" »
Script “/Users/hgneng/Downloads/aa1.praat” not completed.
Praat: script command <<aa1.praat>> not completed.
Here is the content of praat script:
sound = Read from file: "/Users/hgneng/e-guidedog/jyutping-wong/aa1.wav"
endtime = Get end time
To Manipulation... 0.01 75 600
selectObject: sound
Create DurationTier: "aa1", 0, endtime
Add point: 0, 3
selectObject: "Manipulation aa1"
plusObject: "DurationTier aa1"
Replace duration tier
minusObject: "DurationTier aa1"
Get resynthesis (overlap-add)
removeObject: sound
removeObject: "Manipulation aa1"
removeObject: "DurationTier aa1"
Save as WAV file... "/Users/hgneng/Downloads/aa2.wav"
Change
Save as WAV file... "/Users/hgneng/Downloads/aa2.wav"
to
Save as WAV file: "/Users/hgneng/Downloads/aa2.wav"
will fix the issue.

Identify CD drive and eject using bat or vbs while in WinPE without external files

I need to identify the CD drive and eject the tray. This is executed while booted in WinPE, so the WMP eject function is not available. This script will be used on various computer models/configurations. I'm currently using this:
For Each d in CreateObject("Scripting.FileSystemObject").Drives
CreateObject("Shell.Application").Namespace(17).ParseName("D:\").InvokeVerb("Eject")
Next
It works, but sometimes it errors and requires user interaction before it ejects. I suspect that it's because of the hardcoded D:\ drive letter, but I could be completely wrong. I need this to work without 3rd party utilities.
Use the DriveType property of the Drive object:
For Each d in CreateObject("Scripting.FileSystemObject").Drives
WScript.sleep 60
If d.DriveType = 4 Then
CreateObject("Shell.Application").Namespace(17).ParseName(d.DriveLetter & ":\").InvokeVerb("Eject")
End If
Next
Here is code that uses Media Player to eject; I'm not sure how easy it would be to invoke from your WinPE environment:
' http://www.msfn.org/board/topic/45418-vbscript-for-openingclosing-cd/
' http://waxy.org/2003/03/open_cdrom_driv/
Set oWMP = CreateObject("WMPlayer.OCX.7" )
Set colCDROMs = oWMP.cdromCollection
For d = 0 to colCDROMs.Count - 1
colCDROMs.Item(d).Eject
Next 'null
Plan B would be to download a copy of "eject.exe", and include it on your WinPE media:
http://www.911cd.net/forums/index.php?showtopic=2931&hl=cd+eject

How to add a Local Printer using VBScript on Windows 7?

I have a Windows 7 64bit pc, I'm trying to add a Local Printer which automatically installs the driver and shares the printer once it is done.
The port is a Loopback IP Address (127.0.0.1) and it uses the Zebra (ZDesigner LP 2844) Driver. (Which you can get here: http://www.zebra.com/us/en/support-downloads/desktop/lp-2844.html )
My current script works great on XP but not so good on Windows 7. It comes up with the error
"Microsoft VBScript runtime error:ActiveX component can't create object: 'Port.Port.1' for my script AddPort.vbs
The following script is called AddPort.vbs
'ADDING:
dim oPort
dim oMaster
set oPort = CreateObject("Port.Port.1")
set oMaster = CreateObject("PrintMaster.PrintMaster.1")
wscript.echo "Adding port to local machine...."
'Indicate where to add the port. Double quotes ("" ) stand for the local computer, which is the default, or put "\\servername"
oPort.ServerName = ""
'The name of the port cannot be omitted.
oPort.PortName = "CustomPortName"
'The type of the port can be 1 (TCP RAW), 2 (TCP LPR), or 3 (standard local).
oPort.PortType = 3
'For TCP RAW ports. Default is 9100.
oPort.PortNumber = 9101
'Try adding the port.
oMaster.PortAdd oPort
'Test for the status.
If Err <> 0 then
wscript.echo "Error " & Err & " occurred while adding port"
End If
The Following script is called AddPrinter.vbs
This script shows the error "Microsoft VBScript runtime error:ActiveX component can't create object: PrintMaster.PrintMaster.1
' Adding a Printer
' The sample code in this section creates any required objects, adds a printer to a remote server, and configures some driver and port information.
dim oMaster
dim oPrinter
wscript.echo "Adding VirtualPrinter printer to local machine...."
'The following code creates the required PrintMaster and Printer objects.
set oMaster = CreateObject("PrintMaster.PrintMaster.1")
set oPrinter = CreateObject("Printer.Printer.1")
'The following code specifies the name of the computer where the printer will be added. To specify the local
'computer, either use empty quotes (“”) for the computer name, or do not use the following line of code. If
'ServerName is not set, the local computer is used. Always precede the name of a remote computer with two backslashes (\\).
oPrinter.ServerName = ""
'The following code assigns a name to the printer. The string is required and cannot be empty.
oPrinter.PrinterName = "VirtualPrinter"
'The following code specifies the printer driver to use. The string is required and cannot be empty.
oPrinter.DriverName = "ZDesigner LP 2844"
'The following code specifies the printer port to use. The string is required and cannot be empty.
oPrinter.PortName = "LoopBack"
'The following code specifies the location of the printer driver. This setting is optional, because by default
'the drivers are picked up from the driver cache directory.
'oPrinter.DriverPath = "c:\drivers"
'The following code specifies the location of the INF file. This setting is optional, because by default the INF
'file is picked up from the %windir%\inf\ntprint.inf directory.
'oPrinter.InfFile = "c:\winnt\inf\ntprint.inf"
oPrinter.PrintProcessor = "winprint"
'The following code adds the printer.
oMaster.PrinterAdd oPrinter
'The following code uses the Err object to determine whether the printer was added successfully.
if Err <> 0 then
wscript.echo "Error " & Err & " occurred while adding VirtualPrinter"
else
wscript.echo "Printer added successfully"
end if
' To configure other printer settings, such as comments, create a Printer object and then call PrintMaster's method PrinterSet.
wscript.echo "Configuring printer...."
oPrinter.Comment = "Virtual printer to capture labels"
oPrinter.ShareName = "VirtualPrinter"
oPrinter.Shared = true
oPrinter.Local = true
oMaster.PrinterSet oPrinter
if Err <> 0 then
wscript.echo "Error " & Err & " occurred while changing settings for VirtualPrinter"
end if
Is there any other way I can create a Local Printer, Set the Driver, Port Number and Port Name and Share Name and Print Processor using vbscript in Windows 7???
Thank you in advance, the best response will receive points.
This is just what you need, for Windows 7:
The seven printer utilities, shown later, are located in the C:\Windows\System32\Printing_Admin_Scripts\en-US folder, which is not listed in the path. Therefore, you must actually change to this folder in order to run the utilities. And, since these utilities are designed to be run from the command line, you need to launch them from a Command Prompt window and run them using Windows Script Host's command-line-based script host (Cscript.exe).
Windows 7's VBScript printing utilities
VBScript File | What it does
---------------------------------------------
Prncnfg.vbs | Printer configuration
Prndrvr.vbs | Printer driver configuration
Prnjobs.vbs | Print job monitoring
Prnmngr.vbs | Printer management
Prnport.vbs | Printer port management
Prnqctl.vbs | Printer queue management
Pubprn.vbs | Publish a printer to Active Directory
Hope this works for you
I found another way to automate adding the printer, first I created a batch file then I used the prnmngr.vbs which comes with Windows 7 to automatically add the printer for me. For this to work I already had the Zebra driver installed on the machine (but the concept would be the same for any other type of printer). Then I ran the batch file.
Following shows how I did it, I've added the batch file text here:
Name the file: AddPrinter.bat
rem first change the directory to the script location
cd %WINDIR%\System32\Printing_Admin_Scripts\en-US\
rem vbs script path: %WINDIR%\System32\Printing_Admin_Scripts\en-US\Prnmngr.vbs
rem first add the port, specify name of port, assign it an IP Address, specify the type and the Port.
cscript prnport.vbs -a -r "LoopBack" -h 127.0.0.1 -o raw -n 9100
cscript prnport.vbs -a -r "LoopBack_2" -h 127.0.0.1 -o raw -n 9101
pause
rem specify the name of the new printer, specify the driver, specify the port it will use.
cscript prnmngr.vbs -a -p "VirtualPrinter" -m "ZDesigner LP 2844" -r "LoopBack"
pause
cscript prnmngr.vbs -a -p "Zebra LP2844" -m "ZDesigner LP 2844" -r "USB0001"
rem cscript prnmngr.vbs -a -p "Zebra GK420d" -m "ZDesigner GK420d" -r "LPT1:"
rem cscript prnmngr.vbs -a -p "Zebra GC420d" -m "ZDesigner GC420d" -r "COM1:"
pause
NET STOP SPOOLER
NET START SPOOLER
pause
To customise this you can use these websites as a reference;
http://technet.microsoft.com/en-us/library/cc725868(v=ws.10).aspx
http://technet.microsoft.com/en-us/library/bb490974.aspx
http://blog.ogwatermelon.com/?p=3489
http://winadminnotes.wordpress.com/2010/02/19/how-to-manage-printers-and-printer-drivers-remotely-from-command-line/
http://technet.microsoft.com/en-us/library/cc754352(v=ws.10).aspx

Resources