LoginSignup
4
5

More than 5 years have passed since last update.

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

Posted at

説明

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

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

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5