How to stream audio for only a known duration using swift

强颜欢笑 提交于 2019-12-04 16:21:45

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")
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!