Media AVconvert

ムービーmp4変換


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use framework "AVFoundation"
use framework "CoreMedia"
use scripting additions

property refMe : a reference to current application
property refZero : a reference to refMe's kCMTimeZero
set appFileManager to refMe's NSFileManager's defaultManager()

#############################
###入力ファイル
#############################
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
############ デフォルトロケーション
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
set aliasDefaultLocation to (ocidDesktopDirPathURL's absoluteURL()) as alias
####UTIリスト
set listUTI to {"public.movie"}
####ダイアログを出す
set aliasFilePath to (choose file with prompt "ムービーファイルを選んでください" default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
###入力ファイル
set strFilePath to (POSIX path of aliasFilePath) as text
set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
##
set ocidFileName to ocidFilePath's lastPathComponent()
set ocidBaseFileName to ocidFileName's stringByDeletingPathExtension()
#############################
###テンポラリーパス
#############################
set ocidTempDirURL to appFileManager's temporaryDirectory()
##
set ocidUUID to refMe's NSUUID's alloc()'s init()
set ocidUUIDString to ocidUUID's UUIDString
set ocidTemporaryDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:(true)
##フォルダを作っておく
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidTemporaryDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
#############################
###保存先
#############################
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSMoviesDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidMoviesDirPathURL to ocidURLsArray's firstObject()
set ocidSaveDirPathURL to ocidMoviesDirPathURL's URLByAppendingPathComponent:("AVAssetExport")
##フォルダを作っておく
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
###上書きチェック
set numCnt to 0 as number
set strSaveFileName to ocidBaseFileName's stringByAppendingPathExtension:("mp4")
repeat 100 times
  ###保存先URL
  set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName)
  set ocidSaveFilePath to ocidSaveFilePathURL's |path|()
  set boolExist to appFileManager's fileExistsAtPath:(ocidSaveFilePath) isDirectory:(false)
  ##
  if boolExist is true then
    set numCnt to numCnt + 1 as number
    set strZeroSup to "000" as text
    set strZeroSup to (strZeroSup & (numCnt as text)) as text
    set strZeroSup to (text -3 through -1 of strZeroSup) as text
    set strZeroSupFileName to ocidBaseFileName's stringByAppendingPathExtension:(strZeroSup)
    set strSaveFileName to strZeroSupFileName's stringByAppendingPathExtension:("mp4")
  else
log "保存先パス: " & ocidSaveFilePath as text
    exit repeat
  end if
end repeat
#############################
### ムービー読み込み
#############################
set ocidReadAsset to refMe's AVAsset's assetWithURL:(ocidFilePathURL)
set ocidReadAssetTrackArray to ocidReadAsset's tracks()
#set ocidReadAssetTrackArray to ocidReadAsset's tracksWithMediaType:(refMe's AVMediaTypeVideo)
set ocidVideoTrack to ocidReadAssetTrackArray's firstObject()
#
set ocidAssetTrackTimeRange to ocidVideoTrack's timeRange()
#############################
### 書き出し
#############################

set ocidExportSession to refMe's AVAssetExportSession's alloc()'s initWithAsset:(ocidReadAsset) presetName:("AVAssetExportPresetHighestQuality")
ocidExportSession's setOutputURL:(ocidSaveFilePathURL)
ocidExportSession's setOutputFileType:(refMe's AVFileTypeMPEG4)

ocidExportSession's setTimeRange:(ocidAssetTrackTimeRange)
ocidExportSession's setShouldOptimizeForNetworkUse:false
ocidExportSession's setCanPerformMultiplePassesOverSourceMediaData:true
ocidExportSession's setDirectoryForTemporaryFiles:(ocidTemporaryDirPathURL)
ocidExportSession's exportAsynchronouslyWithCompletionHandler:(missing value)


log "########################################"
set numStatusNo to ocidExportSession's status()
log "status:\t" & numStatusNo
(*
AVAssetExportSessionStatusUnknown:0
AVAssetExportSessionStatusWaiting:1
AVAssetExportSessionStatusExporting:2
AVAssetExportSessionStatusCompleted:3
AVAssetExportSessionStatusFailed:4
AVAssetExportSessionStatusCancelled:5
*)
set progress total steps to 1
set progress completed steps to 0
set progress description to "書出"

repeat
  set numProgress to ocidExportSession's progress()
  set numProgressPer to numProgress * 100 as integer
  set progress additional description to "状況:" & numProgressPer & "%"
  set progress completed steps to numProgress
  set numStatusNo to ocidExportSession's status()
  if numStatusNo > 2 then
    exit repeat
  end if
delay 1
end repeat
log "status:\t" & numStatusNo

set ocidReadAsset to ""
set ocidExportSession to ""

## Finder で開く
set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
appSharedWorkspace's activateFileViewerSelectingURLs:({ocidSaveDirPathURL})



return

|

[avconvert]/usr/bin/avconvert を使ってビデオの書き出し

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSArray : a reference to refMe's NSArray
property refNSDate : a reference to refMe's NSDate
property refNSCalendar : a reference to refMe's NSCalendar
property refNSTimeZone : a reference to refMe's NSTimeZone
property refNSDateFormatter : a reference to NSDateFormatter
-->(*__NSCFConstantString*)



###入力
tell application "Finder"
set aliasDefaultLocation to (path to desktop folder from user domain) as alias
end tell
####UTIリスト PDFのみ
set listUTI to {"public.movie"}

####ダイアログを出す
set aliasFilePath to (choose file with prompt "ムービーファイルを選んでください" default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
set strFilePath to POSIX path of aliasFilePath
set ocidFilePath to refNSString's stringWithString:strFilePath
set ocidFileName to ocidFilePath's lastPathComponent()
set ocidBaseFileName to ocidFileName's stringByDeletingPathExtension()
####入力ファイル関連
################################################
####出力メディアフォーマット関連

set listChooseType to {"LowQuality", "MediumQuality", "HighestQuality", "HEVCHighestQuality", "HEVCHighestQualityWithAlpha", "640x480", "960x540", "1280x720", "1920x1080", "3840x2160", "HEVC1920x1080", "HEVC3840x2160", "HEVC1920x1080WithAlpha", "HEVC3840x2160WithAlpha", "HEVC7680x4320", "AppleM4V480pSD", "AppleM4V720pHD", "AppleM4V1080pHD", "AppleM4ViPod", "AppleM4VAppleTV", "AppleM4VCellular", "AppleM4VWiFi", "AppleProRes422LPCM", "AppleProRes4444LPCM", "Passthrough", "AppleM4A"} as list
try
set objResponse to (choose from list listChooseType with title "出力形式" with prompt "フォーマットを選んでください" default items (item 3 of listChooseType) OK button name "OK" cancel button name "キャンセル" with multiple selections allowed without empty selection allowed)
on error
log "エラーしました"
return
end try
if objResponse is false then
log "キャンセルしました"
return
end if
set strPresetName to ("Preset" & objResponse) as text

####################################################
set ocidPresetArray to refNSArray's arrayWithArray:listChooseType
set numChooseListNo to (ocidPresetArray's indexOfObject:(objResponse as text)) as integer
set numChooseListNo to numChooseListNo + 1 as integer
log numChooseListNo
####################################################
###出力
set strDateNO to doGetDateNo("yyyyMMdd_hhmmss") as text
###ファイル名+拡張子
if (objResponse as text) is "AppleM4A" then
set strExportFileName to ("" & ocidBaseFileName & "_" & strDateNO & ".m4a") as text
else if (objResponse as text) contains "M4V" then
set strExportFileName to ("" & ocidBaseFileName & "_" & strDateNO & ".m4v") as text
else
set strExportFileName to ("" & ocidBaseFileName & "_" & strDateNO & ".mov") as text
end if
####

set strDefaultName to strExportFileName as text
set strPromptText to "名前を決めてください"

set aliasDistFilePath to (choose file name default location aliasDefaultLocation default name strDefaultName with prompt strPromptText) as «class furl»
set strDistFilePath to POSIX path of aliasDistFilePath as text

####################################################
###
##
if (objResponse as text) is "AppleM4A" then
set strCommandText to ("/usr/bin/avconvert --source \"" & strFilePath & "\" --output \"" & strDistFilePath & "\" --preset " & strPresetName & " --multiPass --disableFastStart --disableMetadataFilter --progress --verbose ") as text
else if (objResponse as text) contains "M4V" then
set strCommandText to ("/usr/bin/avconvert --source \"" & strFilePath & "\" --output \"" & strDistFilePath & "\" --preset " & strPresetName & " --progress --verbose ") as text

else
set strCommandText to ("/usr/bin/avconvert --source \"" & strFilePath & "\" --output \"" & strDistFilePath & "\" --preset " & strPresetName & " --multiPass --disableFastStart --disableMetadataFilter --progress --verbose ") as text
end if



##do shell script strCommandText

tell application "Terminal"
launch
activate
set objWindowID to (do script "\n\n")
delay 1
tell objWindowID
do script strCommandText in objWindowID
end tell

end tell





to doGetDateNo(strDateFormat)
####日付情報の取得
set ocidDate to refNSDate's |date|()
###日付のフォーマットを定義
set ocidNSDateFormatter to refNSDateFormatter's alloc()'s init()
ocidNSDateFormatter's setLocale:(refMe's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
ocidNSDateFormatter's setDateFormat:strDateFormat
set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:ocidDate
set strDateAndTime to ocidDateAndTime as text
return strDateAndTime
end doGetDateNo

|

[Man]avconvert

AVCONVERT(1)                          General Commands Manual                          AVCONVERT(1)


NAME

     avconvert movie conversion tool


SYNOPSIS

     avconvert [-hv] -s <source_media> -o <output_movie> -p <preset_name>


DESCRIPTION

     avconvert is a tool that converts source media files to different file types for sharing on

     the web or loading onto devices.  The tool will not allow protected content to be converted.

     Only one video and one audio track is preserved through the conversion, along with metadata

     tracks.  The tool will never resize the video higher than the source dimensions.  If the

     preset internal dimensions are larger than that of the source, the conversion will maintain

     the source dimensions.  The file extension provided for the output movie will determine the

     output file type.


     --source | -s file       The source media file to be converted.


     --output | -o file       The output movie file to be created.


     --preset | -p name       Use the specified preset for file conversion.  All presets encode

                              using AVC (H.264) encoding unless otherwise specified in the preset

                              name.  Use --help to get the full list.


                                    Preset640x480                      A 480p Standard Definition

                                                                       preset with H.264 video and

                                                                       AAC audio.

                                    Preset960x540                      A 540p preset with H.264

                                                                       video and AAC audio.

                                    Preset1280x720                     A 720p High Definition

                                                                       preset with H.264 video and

                                                                       AAC audio.

                                    Preset1920x1080                    A 1080p High Definition

                                                                       preset with H.264 video and

                                                                       AAC audio.

                                    Preset3840x2160                    A 2160p Ultra High

                                                                       Definition preset with H.264

                                                                       video and AAC audio.

                                    PresetAppleM4A                     An audio-only preset with

                                                                       AAC audio.

                                    PresetAppleM4V480pSD               A legacy 480p Standard

                                                                       Definition preset with H.264

                                                                       video and AAC audio suitable

                                                                       for playing on Apple

                                                                       devices.

                                    PresetAppleM4V720pHD               A legacy 720p High

                                                                       Definition preset with H.264

                                                                       video and AAC audio suitable

                                                                       for playing on Apple

                                                                       devices.

                                    PresetAppleM4V1080pHD              A legacy 1080p High

                                                                       Definition preset with H.264

                                                                       video and AAC audio suitable

                                                                       for playing on Apple


                                    PresetAppleM4VAppleTV              A legacy preset with H.264

                                                                       video and AAC audio suitable

                                                                       for playing on older AppleTV

                                                                       models.

                                    PresetAppleM4VCellular             A legacy, smaller than

                                                                       Standard Definition, preset

                                                                       with H.264 video and AAC

                                                                       audio suitable for playing

                                                                       on Apple devices when

                                                                       streamed over a cellular

                                                                       network.

                                    PresetAppleM4ViPod                 A legacy Standard Definition

                                                                       preset with H.264 video and

                                                                       AAC audio suitable for

                                                                       playing on an iPod.

                                    PresetAppleM4VWiFi                 A legacy, smaller than

                                                                       Standard Definition, preset

                                                                       with H.264 video and AAC

                                                                       audio suitable for playing

                                                                       on Apple devices when

                                                                       streamed over a WiFi

                                                                       network.

                                    PresetAppleProRes422LPCM           A preset with Apple ProRes

                                                                       422 video and LPCM audio.

                                    PresetAppleProRes4444LPCM          A preset with Apple ProRes

                                                                       4444 video and LPCM audio.

                                    PresetHEVC1920x1080                A 1080p High Definition

                                                                       preset with HEVC video and

                                                                       AAC audio.

                                    PresetHEVC1920x1080WithAlpha       A 1080p High Definition

                                                                       preset with HEVC alpha video

                                                                       and AAC audio.  If a non-

                                                                       alpha source is selected, an

                                                                       error will occur.

                                    PresetHEVC3840x2160                A 2160p Ultra High

                                                                       Definition preset with HEVC

                                                                       video and AAC audio.

                                    PresetHEVC3840x2160WithAlpha       A 2160p Ultra High

                                                                       Definition preset with HEVC

                                                                       alpha video and AAC audio.

                                                                       If a non-alpha source is

                                                                       selected, an error will

                                                                       occur.

                                    PresetHEVC7680x4320                An 8K preset with HEVC video

                                                                       and AAC audio.

                                    PresetHEVCHighestQuality           A high quality preset with

                                                                       HEVC video and AAC audio.

                                    PresetHEVCHighestQualityWithAlpha  A high quality preset with

                                   PresetHEVCHighestQualityWithAlpha  A high quality preset with

                                                                       HEVC alpha video and AAC

                                                                       audio.  If a non-alpha

                                                                       source is selected, an error

                                                                       will occur.

                                    PresetHighestQuality               A high quality preset with

                                                                       H.264 video and AAC audio.

                                    PresetLowQuality                   A low quality, smaller than

                                                                       Standard Definition, preset

                                                                       with H.264 video and AAC

                                                                       audio.

                                    PresetMediumQuality                A medium quality, smaller

                                                                       than Standard Definition,

                                                                       preset with H.264 video and

                                                                       AAC audio.

                                    PresetPassthrough                  A preset that passes through

                                                                       the video and audio tracks,

                                                                       without conversion.


OOPTIONS

     --disableFastStart       Disable fast-start movie creation.  Reduces disk accesses if fast-

                              start is not required.


     --disableMetadataFilter  Disable the metadata filter.  Use with caution.  This will allow

                              privacy sensitive source metadata to be preserved in the output file.

                              This may include information such as the location of the video, time

                              when the video was recorded, video capture device information, etc.

                              If this option is not specified, the aforementioned source metadata

                              is not present in the output file.


     --duration num           Trim the output movie to num seconds (decimal allowed).  Default is

                              end of file.


     --help | -h              Print command usage and list available preset names.


     --multiPass              Perform a higher quality multi-pass encode in the conversion.


     --progress | -prog       Display progress during the conversion (default with -v).


     --replace                Overwrite the output file, if it already exists.


     --start num              Skip the first num seconds (decimal allowed) of the source movie.

                              Default is beginning of file.


     --verbose | -v           Print additional information about the conversion.


EXAMPLES

     Convert the source movie from 4k HEVC to 720p AVC using the 1280x720 encoding preset:


          avconvert --source 4k_hevc_movie.mov --output 720p_avc_movie.mov --preset Preset1280x720


     Convert the source movie from 4k AVC to 4K HEVC using the HEVCHighestQuality encoding preset:


          avconvert -s 4k_avc_movie.mov -o 4k_hevc_movie.mov -p PresetHEVCHighestQuality


     Skip the first 3.5 seconds of the source movie and only convert the next 30 seconds:


          avconvert --source source_movie.mov --output trimmed_movie.mov -p PresetMediumQuality

     --start 3.5 --duration 30


     Convert the source movie from a QuickTime movie file to an MPEG-4 file:


          avconvert -s source_movie.mov -o output_movie.mp4 -p PresetLowQuality


HISTORY

     avconvert command first appeared in Mac OS X 10.7.


     64-bit implementation introduced in Mac OS X 10.15.


macOS                                     October 8, 2021                                     macOS

|

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat AddOn Acrobat Annotation Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat JS Acrobat Manifest Acrobat Menu Acrobat Open Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat python Acrobat Reader Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin Support Admin System Information Admin Tools Admin Users Admin Volumes Adobe Adobe FDKO Adobe RemoteUpdateManager AppKit Apple AppleScript AppleScript do shell script AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript System Events AppleScript System Events Plist AppleScript Video Applications AppStore Archive Attributes Automator BackUp Barcode Barcode QR Barcode QR Decode Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome CIImage CityCode CloudStorage Color com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time delimiters Desktop Device Diff Disk Dock DropBox Droplet eMail Encode % Encode Decode Encode UTF8 Error EXIFData ffmpeg File Finder Firefox Folder FolderAction Fonts GIF github Guide HTML HTML Entity Icon Illustrator Image Events Image2PDF ImageOptim iPhone iWork Javascript Jedit Json Label Leading Zero List locationd LRC lsappinfo LSSharedFileList m3u8 Mail MakePDF Map Math Media Media AVAsset Media AVconvert Media AVFoundation Media AVURLAsset Media Movie Media Music Memo Messages Microsoft Microsoft Edge Microsoft Excel Mouse Music NetWork Notes NSArray NSArray Sort NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSColor NSColorList NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSPrintOperation NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth OneDrive PDF PDFAnnotation PDFAnnotationWidget PDFContext PDFDisplayBox PDFDocumentPermissions PDFImageRep PDFKit PDFnUP PDFOutline perl Photoshop PlistBuddy pluginkit postalcode PostScript prefPane Preview Python QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver SF Symbols character id SF Symbols Entity sips Skype Slack Sound Spotlight sqlite SRT StandardAdditions Swift System Settings TCC TemporaryItems Terminal Text Text CSV Text MD Text TSV TextEdit Tools Translate Trash Twitter Typography UI Unit Conversion UTType valueForKeyPath Video VisionKit Visual Studio Code VMware Fusion Wacom webarchive webp Wifi Windows XML XML EPUB XML OPML XML Plist XML RSS XML savedSearch XML SVG XML TTML XML webloc XML XMP YouTube zoom