FFmpeg を使った iOS・macOS での音声抽出
Swift を使い、動画の最初の音声トラックを音声のみの .m4a ファイルとして保存します。macOS では、FFmpeg で互換性のある音声を再エンコードせずにコピーできます。iOS では、AVFoundation がアプリ内で AAC 音声をエクスポートします。以下のサンプルは既存の出力先を保護し、エクスポートの失敗を報告します。
Apple プラットフォームでの FFmpeg の概要
FFmpeg は、互換性のある音声ストリームを再エンコードせずにコピーできます。macOS のサンプルは、Foundation の Process API を通じて、ローカルの FFmpeg 実行ファイルを起動します。この API は iOS では利用できません。iOS では、Apple 標準の AVFoundation フレームワークと Apple M4A エクスポートプリセットを使います。
Apple プラットフォームでの音声抽出の準備
FFmpegKit は開発を終了しています。作者による開発終了のお知らせと後継に関する情報では、ソースコードとして配布される FFmpegKitNext が案内されています。これらのサンプルに FFmpegKit のバイナリやサードパーティーの Swift パッケージは不要です。
FFmpeg と Swift の準備
Xcode がインストールされ、ffprobe を含む動作可能な FFmpeg 一式が
PATH に配置された Mac を用意してください。インストール方法は、Apple の Xcode ダウンロードと
FFmpeg ダウンロードページに掲載されています。このチュートリアルは、これらのツールのインストール後から始まります。システムソフトウェアのインストールは行いません。
Swift ファイルを保存する前に、新しい作業ディレクトリで次の確認コマンドを実行してください。
command -v swiftc >/dev/null &&
command -v ffmpeg >/dev/null &&
command -v ffprobe >/dev/null &&
swiftc --version && ffmpeg -version && ffprobe -version
動作確認済みの環境は、macOS 26.6.2、Xcode 27.0、Swift 5 言語モードの Swift 6.4、FFmpeg および ffprobe 9.0.2、iOS 27.0 シミュレーターです。古い OS バージョンと実機は、このチュートリアルの検証対象外です。完全版の Xcode には iOS SDK とシミュレーターが含まれます。
AAC 音声トラックを含む破損のないローカル MP4 を、作業ディレクトリに
sample video.mp4 という名前で用意してください。抽出は一度に一件ずつ実行してください。iOS のサンプルは、バンドル内のファイルとアプリ所有の Documents ストレージを使います。外部ファイルプロバイダー、ファイルピッカーの権限、バックグラウンドでのエクスポートは扱いません。
動画ファイルからの音声ストリームの抽出
FFmpeg を使う方法では、-map 0:a:0 で最初の音声ストリームを選択します。M4A へのストリームコピーには、AAC などの互換性のあるコーデックが必要です。AVFoundation を使う方法では、最初の音声トラックを選択し、AVAssetExportPresetAppleM4A でエクスポートします。音声が再エンコードされる場合があり、バイト単位で同一のコピーにはなりません。
音声抽出の手順
次のコードを AudioExtraction.swift として保存してください。各処理は、出力先と同じ階層に新しいディレクトリを作って書き込み、成功した場合にのみ結果を出力先に配置し、失敗時には一時ファイルを削除します。アプリが読み取れるローカルファイルの URL と、既存の書き込み可能なディレクトリ内の出力 URL を渡してください。通常の成功時やエラーがスローされた場合には、一時ディレクトリが削除されます。プロセスが強制終了すると、一時ディレクトリが残る場合があります。
import AVFoundation
import Foundation
enum AudioExtractionError: Error {
case invalidPaths, outputExists, noAudio, exportUnavailable, exportFailed
}
private func extractionDirectory(inputURL: URL, outputURL: URL) throws -> URL {
let files = FileManager.default
guard inputURL.isFileURL, outputURL.isFileURL,
files.isReadableFile(atPath: inputURL.path),
outputURL.pathExtension.lowercased() == "m4a" else {
throw AudioExtractionError.invalidPaths
}
guard !files.fileExists(atPath: outputURL.path) else {
throw AudioExtractionError.outputExists
}
let directory = outputURL.deletingLastPathComponent()
.appendingPathComponent("audio-\(UUID().uuidString)", isDirectory: true)
try files.createDirectory(at: directory, withIntermediateDirectories: false)
return directory
}
#if os(macOS)
// This blocking function belongs on a worker queue when called from a macOS UI.
func extractAudioWithFFmpeg(from videoURL: URL, to outputURL: URL, ffmpegURL: URL) throws {
let directory = try extractionDirectory(inputURL: videoURL, outputURL: outputURL)
defer { try? FileManager.default.removeItem(at: directory) }
let temporaryOutput = directory.appendingPathComponent("audio.m4a")
let process = Process()
process.executableURL = ffmpegURL
process.environment = [:]
process.arguments = [
"-nostdin", "-hide_banner", "-loglevel", "error", "-n",
"-protocol_whitelist", "file,pipe", "-i", videoURL.path,
"-map", "0:a:0", "-vn", "-c:a", "copy", "-f", "ipod", temporaryOutput.path
]
// In this command-line example, diagnostics go to stderr without a pipe that could fill up.
process.standardError = FileHandle.standardError
try process.run()
process.waitUntilExit()
guard process.terminationReason == .exit, process.terminationStatus == 0 else {
throw AudioExtractionError.exportFailed
}
try FileManager.default.moveItem(at: temporaryOutput, to: outputURL)
}
#endif
func extractAudioWithAVFoundation(from videoURL: URL, to outputURL: URL) async throws {
let directory = try extractionDirectory(inputURL: videoURL, outputURL: outputURL)
defer { try? FileManager.default.removeItem(at: directory) }
let temporaryOutput = directory.appendingPathComponent("audio.m4a")
let asset = AVURLAsset(url: videoURL)
guard let sourceTrack = try await asset.loadTracks(withMediaType: .audio).first else {
throw AudioExtractionError.noAudio
}
let composition = AVMutableComposition()
guard let track = composition.addMutableTrack(
withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid
) else {
throw AudioExtractionError.exportUnavailable
}
let timeRange = try await sourceTrack.load(.timeRange)
try track.insertTimeRange(timeRange, of: sourceTrack, at: .zero)
guard let session = AVAssetExportSession(
asset: composition, presetName: AVAssetExportPresetAppleM4A
), session.supportedFileTypes.contains(.m4a) else {
throw AudioExtractionError.exportUnavailable
}
session.outputURL = temporaryOutput
session.outputFileType = .m4a
await session.export()
guard session.status == .completed else {
throw AudioExtractionError.exportFailed
}
try FileManager.default.moveItem(at: temporaryOutput, to: outputURL)
}
使用例
macOS のコマンドラインプログラムでは、次のエントリーポイントを、先ほどのファイルと同じ場所に
ExtractAudio.swift として保存してください。実行ファイルは抽出の完了を待ち、失敗時にはゼロ以外の終了ステータスを返します。
import Foundation
@main
struct ExtractAudio {
static func main() async {
let arguments = CommandLine.arguments
guard arguments.count == 4 || arguments.count == 5 else {
FileHandle.standardError.write(Data(
"Usage: extract-audio avfoundation|ffmpeg input output.m4a [ffmpeg-path]\n".utf8
))
exit(1)
}
do {
let input = URL(fileURLWithPath: arguments[2])
let output = URL(fileURLWithPath: arguments[3])
switch arguments[1] {
case "ffmpeg" where arguments.count == 5:
try extractAudioWithFFmpeg(
from: input, to: output, ffmpegURL: URL(fileURLWithPath: arguments[4])
)
case "avfoundation" where arguments.count == 4:
try await extractAudioWithAVFoundation(from: input, to: output)
default:
throw AudioExtractionError.invalidPaths
}
print("Audio extraction successful: \(output.path)")
} catch {
FileHandle.standardError.write(Data("Audio extraction failed.\n".utf8))
exit(1)
}
}
}
swiftc -parse-as-library AudioExtraction.swift ExtractAudio.swift -o extract-audio &&
./extract-audio ffmpeg "sample video.mp4" copied.m4a "$(command -v ffmpeg)" &&
./extract-audio avfoundation "sample video.mp4" encoded.m4a
このコマンドは、ソースファイルと同じ場所に copied.m4a と
encoded.m4a を書き込みます。両方を音声プレーヤーで開き、音声と再生時間を入力と比較してください。ストリームコピーはエンコード済みの AAC ストリームを保持します。AVFoundation は再エンコードする場合があるため、ファイルのバイト列が同一になるとは限りません。
iOS サンプルの実行
Xcode で、インターフェースに SwiftUI を使う iOS App プロジェクトを作成してください。Swift 5 言語モードを使い、インストール済みの iOS 27 シミュレーターを選択します。AudioExtraction.swift をアプリのターゲットに追加し、sample video.mp4 をその Copy Bundle Resources ビルドフェーズに追加してください。macOS 用の ExtractAudio.swift エントリーポイントは、このターゲットに追加しないでください。生成されたアプリとコンテンツビューのファイルを、次の単一の
AudioDemoApp.swift ファイルに置き換えてください。
import Foundation
import SwiftUI
@main
struct AudioDemoApp: App {
var body: some Scene {
WindowGroup { AudioDemoView() }
}
}
struct AudioDemoView: View {
@State private var started = false
@State private var message = "Extracting audio…"
@State private var output: URL?
var body: some View {
VStack(spacing: 16) {
Text(message)
if let output {
ShareLink("Share audio", item: output)
}
}
.padding()
.task {
guard !started else { return }
started = true
do {
guard let input = Bundle.main.url(
forResource: "sample video", withExtension: "mp4"
) else { throw AudioExtractionError.invalidPaths }
let documents = try FileManager.default.url(
for: .documentDirectory, in: .userDomainMask,
appropriateFor: nil, create: true
)
let destination = documents.appendingPathComponent("encoded.m4a")
try await extractAudioWithAVFoundation(from: input, to: destination)
output = destination
message = "Audio saved: encoded.m4a"
} catch {
message = "Extraction failed. Check the input and destination."
}
}
}
}
アプリをビルドして実行してください。ビューが開くと一度だけエクスポートし、完了後に
Audio saved: encoded.m4a と表示します。Share audio を使うと、結果を別のアプリで開いたり保存したりできます。ソースはバンドル内に残り、encoded.m4a はアプリの Documents ディレクトリに保存されます。次回起動時には、既存の出力があるため処理が拒否されます。再度エクスポートするには、別の出力先ファイル名を選ぶか、既存の出力を意図的に削除してください。ファイルを読み取るため、マイクの権限は不要です。
よくある問題への対処
- ファイルアクセス:入力が存在し、出力先の親ディレクトリに書き込めることを確認してください。CLI はローカルのターミナルプログラムです。サンドボックス化された macOS アプリに FFmpeg を組み込むには、別途作業が必要です。iOS のサンプルでは、意図的にアプリのバンドルと Documents ディレクトリ内だけを使います。
- 既存の出力:新しい出力先を選んでください。サンプルは既存のファイルを上書きしません。
- 音声トラックがない場合:音声トラックのない動画ではエラーとなり、新しい出力は作成されません。無音を含むトラックも音声トラックであり、エクスポートできます。
- 未対応のコーデック:音声コーデックを M4A に格納できない場合、FFmpeg のストリームコピーは失敗することがあります。代わりに AAC で再エンコードするか、Apple のフレームワークが対応する入力には AVFoundation を使ってください。
- 診断:FFmpeg の stderr をローカルで調べてください。AVFoundation のデバッグでは、アプリの UI に内部エラーを表示せず、失敗を確認する箇所で
session.errorを調べてください。 - 破損した録画:エクスポートの成功は、完全性の検証にはなりません。メディアツールは不完全な入力を復元できる場合があります。使用前に、出力の実際の再生時間と音声を比較してください。
パフォーマンスの最適化
- エンコード済みストリームを保持する必要がある場合は、
-c:a copyで互換性のある音声をコピーしてください。 - FFmpeg プロセスの終了を待つブロッキング処理は、macOS アプリのメインスレッド以外で実行してください。
- 録画全体を
Data値に読み込むのではなく、サンプルと同様に AVFoundation のエクスポートを await してください。引き続き使用しているexport()とstatusの API は、現在の SDK では非推奨の警告が出ます。Apple のエクスポートガイドでは、新しい OS バージョンを対象とするアプリ向けに、新しいエクスポート API を説明しています。
関連資料
ストリームの選択とエクスポート設定の詳細は、FFmpeg のストリーム選択ドキュメントと、Apple のメディアエクスポートガイドを参照してください。
サーバー側のワークフローについては、Transloadit の音声エンコーディングサービスを参照してください。
