How to stream audio for only a known duration usin

2020-07-26 07:15发布

问题:

I'm using AVPlayer (I don't need to, but I wanna stream it and start playing as soon as possible) to play an m4a file (it's an iTunes audio preview). Only I only want it to play a part of that file. I'm able to set a start time but not an end time.

Using a timer is not working because I'm using URL as a http address. I'm playing as it loads, without downloading the file.

I also saw solutions in Objective-C to use KVO to know when music starts playing but I'm thinking this is not the best approach since I'm using swift and also because of glitches that may occur so the song will not stop at the right moment.

回答1:

You can add a addBoundaryTimeObserverForTimes to your AVPlayer as follow:

update: Xcode 8.3.2 • Swift 3.1

import UIKit
import AVFoundation

class ViewController: UIViewController {
    var player: AVPlayer!
    var observer: Any!
    override func viewDidLoad() {
        super.viewDidLoad()
        guard let url = URL(string: "https://www.example.com/audio.mp3") else { return }
        player = AVPlayer(url: url)
        let boundary: TimeInterval = 30
        let times = [NSValue(time: CMTimeMake(Int64(boundary), 1))]
        observer = player.addBoundaryTimeObserver(forTimes: times, queue: nil) {
            [weak self] time in
            print("30s reached")
            if let observer = self?.observer {
                self?.player.removeTimeObserver(observer)
            }
            self?.player.pause()
        }
        player.play()
        print("started loading")
    }
}