gpt4 book ai didi

ios - 如果 URL 快速失败,如何为 AVPlayer 重新加载数据

转载 作者:行者123 更新时间:2023-11-28 11:42:32 27 4
gpt4 key购买 nike

我有 json 文件,其中包含一些单词的 URL(带有 .mp3)。某些 URL 无效(或有效,但返回错误,因此我无论如何都无法获取数据)。

这个 URL 我用来播放单词的发音。所以,我要抛出 3 个步骤:

  1. 查找特定单词的 URL。如果找不到,那么什么也不会发生
  2. 使用此 URL 初始化 AVPlayerItem 并准备 AVPlayer。当用户按下时,不仅仅是等待。
  3. 当用户按下单词时播放声音

所以,首先,我正在准备我的AVPlayer,以避免播放延迟。

我对多线程有点困惑,我不明白我应该在哪里检查我是否能够播放这个声音,或者我应该使用下一个 URL。

代码:

extension WordCell {

func playPronunciation() {
player?.play()
player?.seek(to: .zero)
}

func prepareForPronunciation() {
if let word = myLabel.text {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
DispatchQueue.global(qos: .userInteractive).async { [weak self] in
let foundURL = self?.findURL(for: word)
if let url = foundURL {
let playerItem = AVPlayerItem(url: url)

//here "playerItem.status" always equals .unknown (cause not initialized yet)
if playerItem.status == .failed {
//self?.giveNextUrl() - will do some code there
}
self?.player = AVPlayer(playerItem: playerItem)
self?.player!.volume = 1.0
}
// this is also not correct, because networking continueing
// but i don't know where to place it
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
}
}

// right now i take URL from file, where there is only one.
// but i will use file with a few URL for one word
private func findURL(for word: String) -> URL? {

if let path = Bundle.main.path(forResource: "data", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? [String: String] {
if let url = jsonResult[word] {
return URL(string: url)
} else {
return nil
}
}
} catch {
return nil
}
}
return nil
}

}

这是一个 json 文件,每个单词有几个 URL

"abel": [
"http://static.sfdict.com/staticrep/dictaudio/A00/A0015900.mp3",
"http://img2.tfd.com/pron/mp3/en/US/d5/d5djdgdyslht.mp3",
"http://img2.tfd.com/pron/mp3/en/UK/d5/d5djdgdyslht.mp3",
"http://www.yourdictionary.com/audio/a/ab/abel.mp3"
],
"abele": [
"http://www.yourdictionary.com/audio/a/ab/abele.mp3",
"http://static.sfdict.com/staticrep/dictaudio/A00/A0016300.mp3",
"http://www.oxforddictionaries.com/media/english/uk_pron/a/abe/abele/abele__gb_2_8.mp3",
"http://s3.amazonaws.com/audio.vocabulary.com/1.0/us/A/1B3JGI7ALNB2K.mp3",
"http://www.oxforddictionaries.com/media/english/uk_pron/a/abe/abele/abele__gb_1_8.mp3"
],

所以,我需要获取第一个 URL 并检查它。如果失败,则在 URL 结束时采取另一个并检查...等等,或者找到一些有效的 URL。所有这些事情都必须在 AVPlayer 尝试播放声音之前完成。

如何实现以及在哪里实现?

请用简单的语言讲述和描述解决方案,因为我是快速和多线程的初学者。

最佳答案

我将使用 AVPlayerItem.Status 属性来查看它何时失败。在当前代码中,您在创建项目后立即检查状态,这将始终产生与初始化 AVPlayerItem 时相同的结果,status 默认情况下未知.

一旦与播放器关联,AVPlayerItem 就会排队。为了能够跟踪状态变化,您需要设置一个观察者。

文档 https://developer.apple.com/documentation/avfoundation/avplayeritem仍然建议使用 addObserver 的“旧式”,但根据您的偏好,我会选择较新的 block 式。

// make sure to keep a strong reference to the observer (e.g. in your controller) otherwise the observer will be de-initialised and no changes updates will occur
var observerStatus: NSKeyValueObservation?


// in your method where you setup your player item
observerStatus = playerItem.observe(\.status, changeHandler: { (item, value) in
debugPrint("status: \(item.status.rawValue)")
if item.status == .failed {
// enqueue new asset with diff url
}
})

您也可以在 AVPlayer 实例上设置类似的观察者。


更新了完整示例- 这段代码远非完美,但展示了观察者的好处

import UIKit
import AVFoundation

class ViewController: UIViewController {
var observerStatus: NSKeyValueObservation?
var currentTrack = -1
let urls = [
"https://sample-videos.com/audio/mp3/crowd-cheerin.mp3", // "https://sample-videos.com/audio/mp3/crowd-cheering.mp3"
"https://sample-videos.com/audio/mp3/wave.mp3"
]
var player: AVPlayer? {
didSet {
guard let p = player else { return debugPrint("no player") }
debugPrint("status: \(p.currentItem?.status == .unknown)") // this is set before status changes from unknown
}
}

override func viewDidLoad() {
super.viewDidLoad()
nextTrack()
}

func nextTrack() {
currentTrack += 1
guard let url = URL(string: urls[currentTrack]) else { return }
let item = AVPlayerItem(url: url)

observerStatus = item.observe(\.status, changeHandler: { [weak self] (item, value) in
switch item.status {
case .unknown:
debugPrint("status: unknown")
case .readyToPlay:
debugPrint("status: ready to play")
case .failed:
debugPrint("playback failed")
self?.nextTrack()
}
})

if player == nil {
player = AVPlayer(playerItem: item)
} else {
player?.replaceCurrentItem(with: item)
}
player?.play()
}
}

关于ios - 如果 URL 快速失败,如何为 AVPlayer 重新加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53361561/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com