20260619

オーディオファイルの変換(m4aに変換する)

オーディオファイルの変換(m4aに変換する)

ダウンロードはこちら
NOTE記事一覧ですnote.com
 

【Safari・FireFox用Script Editorで開く】 |

Audio2M4A.applescript.scpt
ソース
001#!/usr/bin/env osascript
002#coding: utf-8
003----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
004(*
005assetWithURL:の非推奨で代替
006AVURLAssetで読み込みだけど 同期処理で非同期にはしていない
007AVAssetExportPresetAppleM4A設定なので
008AAC-LC
00948 kHz
010256 kbps
011ステレオ で書き出される事が多い(元のファイルに依存あり)
012
013
014v1 初回作成
015v1.1 ダイアログを通常のダイアログに戻した
016v1.2 中間ファイル名をUUIDにしてエラー時に残っても再起動時に削除されるようにした
017v2 クイックアクション用に変更
018
019com.cocolog-nifty.quicktimer.icefloe *)
020----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
021use AppleScript version "2.8"
022use framework "Foundation"
023use framework "AppKit"
024#   use framework "Cocoa"
025use framework "AVFoundation"
026use framework "UniformTypeIdentifiers"
027use scripting additions
028
029property refMe : a reference to current application
030property listAliasFilePath : {} as list
031
032
033########################
034# RUN
035#   on run {listAliasFilePath}
036
037on run
038   
039   if (count of listAliasFilePath) = 0 then
040      ########################
041      # ダイアログ
042      set appFileManager to refMe's NSFileManager's defaultManager()
043      set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
044      set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
045      set aliasDefaultLocation to (ocidDesktopDirPathURL's absoluteURL()) as alias
046      #簡易版
047      set listUTI to {"public.audiovisual-content", "public.movie", "public.audio"} as list
048      
049      set strMes to ("オーディオファイルを選択してください " & return & "m4aオーディオに変換します") as text
050      set strPrompt to ("オーディオファイルを選択してください " & return & "m4aオーディオに変換します") as text
051      try
052         tell application "Finder"
053            tell application "SystemUIServer"
054               activate
055               set listAliasFilePath to (choose file strMes with prompt strPrompt default location aliasDefaultLocation of type listUTI with invisibles and multiple selections allowed without showing package contents) as list
056            end tell
057         end tell
058      on error strErrMes number numErrNo
059         log strErrMes & numErrNo
060         return false
061      end try
062      if listAliasFilePath is {} then
063         return false
064      end if
065   end if
066   
067   set boolDone to (open listAliasFilePath)
068   try
069      with timeout of 3 seconds
070         tell application "System Events" to quit
071      end timeout
072   on error strErrMes number numErrNo
073      log "Quit System Events" & strErrMes & numErrNo
074      return false
075   end try
076   return boolDone
077end run
078
079
080
081########################
082# OPEN
083on open listAliasFilePath
084   
085   set listUTI to {"com.apple.coreaudio-format", "com.apple.immersive-video", "com.apple.m4a-audio", "com.apple.m4v-video", "com.apple.mpeg-4-ringtone", "com.apple.music.mp2", "com.apple.protected-mpeg-4-audio", "com.apple.protected-mpeg-4-audio-b", "com.apple.quicktime-audio", "com.apple.quicktime-movie", "com.audible.aa-audiobook", "com.audible.aax-audiobook", "com.microsoft.waveform-audio", "com.scenarist.closed-caption", "com.sony.wave64", "org.3gpp.adaptive-multi-rate-audio", "org.videolan.mod", "org.videolan.mpeg-stream", "org.videolan.vob", "org.w3.webvtt", "org.xiph.flac", "org.xiph.ogg-audio", "public.3gpp", "public.3gpp2", "public.aac-audio", "public.ac3-audio", "public.aifc-audio", "public.aiff-audio", "public.au-audio", "public.avchd-mpeg-2-transport-stream", "public.avi", "public.dv-movie", "public.enhanced-ac3-audio", "public.mp2", "public.mp3", "public.mp4a-loas", "public.mpeg", "public.mpeg-2-transport-stream", "public.mpeg-2-video", "public.mpeg-4", "public.mpeg-4-audio"} as list
086   
087   set listJobAliasFilePath to {} as list
088   #変換可能なオーディオファイルのみ次工程に回す
089   repeat with itemAliasFilePath in listAliasFilePath
090      set aliasItemFilePath to itemAliasFilePath as alias
091      set recordInfoFor to (info for aliasItemFilePath) as record
092      set boolIsDir to (folder of recordInfoFor) as boolean
093      if boolIsDir is false then
094         set boolIsAlias to (alias of recordInfoFor) as boolean
095         if boolIsAlias is false then
096            set strUTI to (type identifier of recordInfoFor) as text
097            set boolContain to (listUTI contains strUTI) as boolean
098            if boolContain is true then
099               set end of listJobAliasFilePath to aliasItemFilePath
100            end if
101         end if
102      end if
103   end repeat
104   
105   if (count of listJobAliasFilePath) > 0 then
106      set boolDone to doConvert(listJobAliasFilePath)
107   end if
108   
109   return true
110end open
111
112on doConvert(listJobAliasFilePath)
113   set appFileManager to refMe's NSFileManager's defaultManager()
114   
115   ########################
116   # 書き出し先
117   #上書き防止で
118   set strDateNo to doGetDateNo("yyyyMMddhhmmss") as text
119   set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSMusicDirectory) inDomains:(refMe's NSUserDomainMask))
120   set ocidMusicDirPathURL to ocidURLsArray's firstObject()
121   set strExportDirName to ("AVAssetExport/" & strDateNo & "") as text
122   set ocidSaveDirPathURL to ocidMusicDirPathURL's URLByAppendingPathComponent:(strExportDirName) isDirectory:(true)
123   set ocidSaveDirPath to ocidSaveDirPathURL's |path|()
124   set boolDirExists to appFileManager's fileExistsAtPath:(ocidSaveDirPath) isDirectory:(true)
125   if boolDirExists is false then
126      set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s init()
127      ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
128      set listDone to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:(true) attributes:(ocidAttrDict) |error|:(reference)
129   end if
130   
131   ########################
132   #テンポラリ
133   
134   set ocidTempDirURL to appFileManager's temporaryDirectory()
135   set ocidSessionDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:("AVAssetExportSession") isDirectory:(true)
136   set ocidSessionDirPath to ocidSessionDirPathURL's |path|()
137   set boolDirExists to appFileManager's fileExistsAtPath:(ocidSessionDirPath) isDirectory:(true)
138   if boolDirExists is false then
139      set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s init()
140      ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
141      set listDone to appFileManager's createDirectoryAtURL:(ocidSessionDirPathURL) withIntermediateDirectories:(true) attributes:(ocidAttrDict) |error|:(reference)
142   end if
143   #セッションファイル(書き出しファイル)
144   set ocidUUID to refMe's NSUUID's alloc()'s init()
145   set ocidUUIDString to ocidUUID's UUIDString()
146   set ocidSessionFilePathURL to ocidSessionDirPathURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:(false)
147   
148   ########################
149   #出力
150   set ocidSaveURLsArray to refMe's NSMutableArray's alloc()'s init()
151   #プリセット
152   set strPresetName to ("AVAssetExportPresetAppleM4A") as text
153   
154   
155   repeat with itemAliasFilePath in listJobAliasFilePath
156      set aliasFilePath to itemAliasFilePath as alias
157      set strFilePath to (POSIX path of aliasFilePath) as text
158      set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
159      set ocidFilePathStr to ocidFilePathStr's precomposedStringWithCanonicalMapping()
160      set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
161      set ocidFilePath to ocidFilePath's stringByExpandingTildeInPath()
162      set ocidFilePathURL to (refMe's NSURL's fileURLWithPath:(ocidFilePath) isDirectory:(false))
163      #
164      set ocidFileName to ocidFilePathURL's lastPathComponent()
165      set ocidBaseFileName to ocidFileName's stringByDeletingPathExtension()
166      set ocidSaveFileName to (ocidBaseFileName's stringByAppendingPathExtension:("m4a"))
167      set ocidSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(ocidSaveFileName) isDirectory:(false))
168      (ocidSaveURLsArray's addObject:(ocidSaveFilePathURL))
169      ########################
170      #AVAsset
171      set ocidOptionDict to refMe's NSMutableDictionary's alloc()'s init()
172      set ocidReadAsset to (refMe's AVURLAsset's alloc()'s initWithURL:(ocidFilePathURL) options:(ocidOptionDict))
173      #AVAssetTrack
174      set ocidReadAssetTrackArray to ocidReadAsset's tracks()
175      set ocidTrack to ocidReadAssetTrackArray's firstObject()
176      set ocidTrackID to ocidTrack's trackID()
177      set ocidMediaType to ocidTrack's mediaType()
178      set ocidAssetTrackTimeRange to ocidTrack's timeRange()
179      set ocidAssetTrackTimeScale to ocidTrack's naturalTimeScale()
180      set ocidAssetTrackNaturalSize to ocidTrack's naturalSize()
181      set ocidCMTimeFrameDura to ocidTrack's minFrameDuration()
182      set ocidReadAssetDuration to ocidReadAsset's duration()
183      #AVAssetExportSession
184      set ocidExSession to (refMe's AVAssetExportSession's alloc()'s initWithAsset:(ocidReadAsset) presetName:(strPresetName))
185      (ocidExSession's setOutputURL:(ocidSessionFilePathURL))
186      (ocidExSession's setOutputFileType:(refMe's AVFileTypeAppleM4A))
187      (ocidExSession's setTimeRange:(ocidAssetTrackTimeRange))
188      (ocidExSession's setShouldOptimizeForNetworkUse:(false))
189      (ocidExSession's setCanPerformMultiplePassesOverSourceMediaData:(true))
190      (ocidExSession's setDirectoryForTemporaryFiles:(ocidSessionDirPathURL))
191      (ocidExSession's exportAsynchronouslyWithCompletionHandler:(missing value))
192      set numStatusNo to ocidExSession's status()
193      log "status: " & numStatusNo
194      (*
195AVAssetExportSessionStatusUnknown:0
196AVAssetExportSessionStatusWaiting:1
197AVAssetExportSessionStatusExporting:2
198AVAssetExportSessionStatusCompleted:3
199AVAssetExportSessionStatusFailed:4
200AVAssetExportSessionStatusCancelled:5
201*)
202      set progress total steps to 1
203      set progress completed steps to 0
204      set progress description to "書出"
205      repeat
206         set numProgress to ocidExSession's progress()
207         set numProgressPer to numProgress * 100 as integer
208         log "状況:" & numProgressPer & "%"
209         set progress additional description to "状況:" & numProgressPer & "%"
210         set progress completed steps to numProgress
211         set numStatusNo to ocidExSession's status()
212         if numStatusNo > 2 then
213            exit repeat
214         end if
215         delay 1
216      end repeat
217      log "Done: " & numStatusNo
218      #書き出したファイルを移動する
219      set listDone to (appFileManager's moveItemAtURL:(ocidSessionFilePathURL) toURL:(ocidSaveFilePathURL) |error|:(reference))
220      if (first item of listDone) is false then
221         set strErrorNO to (item 2 of listDone)'s code() as text
222         set strErrorMes to (item 2 of listDone)'s localizedDescription() as text
223         refMe's NSLog("■" & strErrorNO & strErrorMes)
224         log ocidExportFilePathURL's |path|() as text
225         log ocidSaveFilePathURL's |path|() as text
226         log "エラーしました" & strErrorNO & strErrorMes
227         display alert "エラーしました" & strErrorNO & strErrorMes
228         return false
229      end if
230      set ocidReadAsset to (missing value)
231      set ocidExSession to (missing value)
232      set ocidReadAssetTrackArray to (missing value)
233   end repeat
234   
235   #
236   set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
237   set boolDone to appSharedWorkspace's openURL:(ocidSaveDirPathURL)
238   set appFinderArray to refMe's NSRunningApplication's runningApplicationsWithBundleIdentifier:("com.apple.finder")
239   set appFinder to appFinderArray's firstObject()
240   set boolDone to appFinder's activateWithOptions:(refMe's NSApplicationActivateIgnoringOtherApps)
241   log boolDone
242   appSharedWorkspace's activateFileViewerSelectingURLs:(ocidSaveURLsArray)
243   
244   
245   return true
246end doConvert
247
248#####################
249#日付情報の取得
250to doGetDateNo(argFormatStrings)
251   set ocidDate to refMe's NSDate's |date|()
252   set ocidNSDateFormatter to refMe's NSDateFormatter's alloc()'s init()
253   set ocidLocation to (refMe's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
254   ocidNSDateFormatter's setLocale:(ocidLocation)
255   ocidNSDateFormatter's setDateFormat:(argFormatStrings)
256   set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:(ocidDate)
257   set strDateAndTime to ocidDateAndTime as text
258   return strDateAndTime
259end doGetDateNo
260
AppleScriptで生成しました