How to stream audio for only a known duration using swift

老子叫甜甜 提交于 2020-01-23 02:57:28

问题


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")
    }
}


来源:https://stackoverflow.com/questions/32082112/how-to-stream-audio-for-only-a-known-duration-using-swift

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