如何使用swift仅传输已知持续时间的音频 [英] How to stream audio for only a known duration using swift

查看:171
本文介绍了如何使用swift仅传输已知持续时间的音频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AVPlayer(我不需要,但我想流式播放并尽快开始播放)播放m4a文件(这是iTunes音频预览)。只有我只想让它播放该文件的一部分。
我可以设置开始时间而不是结束时间。

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.

使用计时器无效,因为我使用URL作为http地址。我正在加载,而不是下载文件。

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.

我还看到Objective-C中的解决方案使用KVO知道音乐何时开始播放但我在想这不是最好的方法,因为我使用swift,也因为可能会出现故障,所以歌曲不会在合适的时刻停止。

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.

推荐答案

您可以将 addBoundaryTimeObserverForTimes 添加到AVPlayer如下所示:

You can add a addBoundaryTimeObserverForTimes to your AVPlayer as follow:

更新: 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")
    }
}

这篇关于如何使用swift仅传输已知持续时间的音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆