VideoFlint / Cabbage

A video composition framework build on top of AVFoundation. It's simple to use and easy to extend.
MIT License
1.52k stars 221 forks source link

Cannot not play audio in time range after added #29

Closed mvn-thanhluu-hn closed 5 years ago

mvn-thanhluu-hn commented 5 years ago

Hi vitoziv, I cannot play audio in a specific time range after added. This is my source code. I cannot play audio1.mp3 after set startTime and duration, if I don't set this, it plays well. Thank you.

    let video1TrackItem: TrackItem = {
        let url = Bundle.main.url(forResource: "video1", withExtension: "mp4")!
        let resource = AVAssetTrackResource(asset: AVAsset(url: url))
        let trackItem = TrackItem(resource: resource)
        trackItem.videoConfiguration.contentMode = .aspectFit
        return trackItem
    }()

   let mp3TrackItem: TrackItem = {
        let url = Bundle.main.url(forResource: "audio1", withExtension: "mp3")!
        let resource = AVAssetTrackResource(asset: AVAsset(url: url))
        let trackItem = TrackItem(resource: resource)
        trackItem.startTime = CMTime(value: 1, timescale: 1)
        trackItem.duration = CMTime(value: 10, timescale: 1)
        return trackItem
    }()

   let timeline = Timeline()
    timeline.videoChannel = [video1TrackItem]
    timeline.audioChannel = [video1TrackItem]
    timeline.audios = [mp3TrackItem]
vitoziv commented 5 years ago

How many seconds does the audio1.mp3 have?

mvn-thanhluu-hn commented 5 years ago

The duration of the file audio1.mp3 is 27 seconds. I get it from here: https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3

docbohanh commented 5 years ago

I'm stuck with the same issue. Check it please, thanks!!

vitoziv commented 5 years ago

Change code

    let mp3TrackItem: TrackItem = {
        let url = Bundle.main.url(forResource: "audio1", withExtension: "mp3")!
        let resource = AVAssetTrackResource(asset: AVAsset(url: url))
        let trackItem = TrackItem(resource: resource)
        trackItem.startTime = CMTime(value: 1, timescale: 1)
        trackItem.duration = CMTime(value: 10, timescale: 1)
        return trackItem
    }()

to

    let mp3TrackItem: TrackItem = {
        let url = Bundle.main.url(forResource: "audio1", withExtension: "mp3")!
        let resource = AVAssetTrackResource(asset: AVAsset(url: url))
        resource.selectedTimeRange = CMTimeRange.init(start: CMTime.zero, end: CMTime(value: 10, timescale: 1))
        let trackItem = TrackItem(resource: resource)
        trackItem.startTime = CMTime(value: 1, timescale: 1)
        return trackItem
    }()

TrackItem's duration is timeline duration, not resource duration

mvn-thanhluu-hn commented 5 years ago

@vitoziv It works. Thank you.