Skip to content

Instantly share code, notes, and snippets.

@SKaplanOfficial
Last active June 27, 2023 14:14
Show Gist options
  • Save SKaplanOfficial/b564edb219a40965c464c284dc9ca3e3 to your computer and use it in GitHub Desktop.
Save SKaplanOfficial/b564edb219a40965c464c284dc9ca3e3 to your computer and use it in GitHub Desktop.
JXA script to record audio and store it into an wav file.
# Expects two arguments: full path to .wav file to export to & duration (seconds) to record.
osascript -l "JavaScript" -e 'function run(argv) { ObjC.import("objc"); ObjC.import("AVFoundation"); const outputURL = $.NSURL.alloc.initFileURLWithPath(argv[0]); const settings = $.NSMutableDictionary.alloc.init; settings.setValueForKey($.kAudioFormatAppleIMA4, $.AVFormatIDKey); settings.setValueForKey(16000, $.AVSampleRateKey); settings.setValueForKey(1, $.AVNumberOfChannelsKey); settings.setValueForKey($.kAudioFileWAVEType, $.AVAudioFileTypeKey); const startDate = $.NSDate.alloc.init; const session = $.objc_getClass("AVAudioSession").sharedInstance; let recorder = null; session.setCategoryError($.AVAudioSessionCategoryRecord, null); session.setActiveError(true, null); session.requestRecordPermission((b) => { recorder = $.objc_getClass("AVAudioRecorder").alloc.initWithURLSettingsError(outputURL, settings, null); recorder.record; }); while (startDate.timeIntervalSinceNow > -argv[1]) { runLoop = $.NSRunLoop.currentRunLoop; today = $.NSDate.dateWithTimeIntervalSinceNow(0.1); runLoop.runUntilDate(today); }; ; recorder.stop; flags = $.AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation; session.setActiveWithFlagsError(false, flags, null); }' "$1" $2
// Reference: https://developer.apple.com/documentation/avfaudio/avaudiorecorder?language=objc
(() => {
ObjC.import("objc");
ObjC.import("AVFoundation");
const outputURL = $.NSURL.alloc.initFileURLWithPath("/Users/exampleUser/Downloads/test.mp4");
const settings = $.NSMutableDictionary.alloc.init
settings.setValueForKey($.kAudioFormatAppleIMA4, $.AVFormatIDKey)
const format = $.objc_getClass("AVAudioFormat").alloc.initWithSettings(settings)
const recorder = $.objc_getClass("AVAudioRecorder").alloc.initWithURLFormatError(outputURL, format, null)
recorder.recordForDuration(10);
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment