avfoundationを使って音声ファイルのトリミング

説明

swift3を使って音声ファイルをトリミングしてみます。およそ4分程度の音声ファイルのうち5秒〜15秒の間だけ切り取るところまでをやっていきます。AVFoundationは覚えることが多く、使い方も面倒臭く、リファレンスを読むだけでは掴みづらい感じがあります。なので良いソースコードを見つけていじるのが良いですね。下記に参照元を貼っておきます。

10715a2dc086df6d3fa8aa37a4d5417d.png

実装

import UIKit
import AVFoundation


class ViewController: UIViewController {

    var asset: AVAsset?

    func createAudioFileFromAsset(_ asset: AVAsset){
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL
        let filePath = documentsDirectory.appendingPathComponent("rendered-audio.m4a")
     if let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A){
            exportSession.canPerformMultiplePassesOverSourceMediaData = true
            exportSession.outputURL = filePath
            exportSession.outputFileType = AVFileTypeAppleM4A
            exportSession.exportAsynchronously {
                _ in
                print("finished: \(filePath) :  \(exportSession.status.rawValue) ")
            }
        }
    }


    @IBAction func exportBtnDidTap(_ sender: Any) {
        guard let asset = asset else {
            return
        }
        createAudioFileFromAsset(asset)
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        let audioAsset = AVURLAsset(url: Bundle.main.url(forResource: "LoveYourself", withExtension: "mp3")!)
        let comp = AVMutableComposition()
        let audioAssetSourceTrack = audioAsset.tracks(withMediaType: AVMediaTypeAudio).first! as AVAssetTrack
        let audioCompositionTrack = comp.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid)

        do {
            try audioCompositionTrack.insertTimeRange(
                CMTimeRangeMake(CMTimeMakeWithSeconds(5, 100000), CMTimeMakeWithSeconds(15, 100000)),
                of: audioAssetSourceTrack,
                at: kCMTimeZero)
        }
        catch { print(error) }
        asset = comp

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

参考

justinlevi/AVAssetExportSession_AVMutableComposition

ソース

github

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事