終於找到一些很好的例子後,我想出了:
let composition = AVMutableComposition()
var playerItem:AVPlayerItem!
var qPlayer:AVQueuePlayer!
var currentAudioTrack:AVAssetTrack!
var compAudioTrack:AVMutableCompositionTrack!
var uurl:URL!
var asset:AVURLAsset!
...
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
} catch let error {
print("i am error:", error)
}
compAudioTrack = composition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())
uurl = (sysMusicPlayer.nowPlayingItem?.assetURL)!
asset = AVURLAsset(url: uurl)
currentAudioTrack = asset.tracks(withMediaType: AVMediaTypeAudio)[0]
assetTimeScale = currentAudioTrack.naturalTimeScale
let a:CMTime = CMTime(seconds: 10, preferredTimescale: assetTimeScale)
let b:CMTime = CMTime(seconds: 42, preferredTimescale: assetTimeScale)
try! compAudioTrack.insertTimeRange(CMTimeRange(start: a, end: b), of: currentAudioTrack, at: CMTimeMake(0, 1))
playerItem = AVPlayerItem(asset: composition)
qPlayer = AVQueuePlayer(playerItem: playerItem)
qPlayer.play()
這是最基本的功能,它可以讓我failr輕易改變歌曲的當前部分通過
compAudioTrack.segments.removeAll()
try! compAudioTrack.insertTimeRange(timeRangeToInsert, of: currentAudioTrack, at: CMTimeMake(0, 1))
qPlayer.insert(playerItem, after: nil)