Nik*_*rov 2 multithreading ios avplayer swift
我有 json 文件,其中包含一些单词 URL(带有 .mp3)。有些 URL 无效(或有效,但返回错误,因此我无论如何都无法获取数据)。
我用这个 URL 来播放单词的发音。所以,我分三步走:
所以,首先,我正在准备我的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
}
Run Code Online (Sandbox Code Playgroud)
}
这是 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"
],
Run Code Online (Sandbox Code Playgroud)
所以,我需要获取第一个 URL 并检查它。如果失败,则在 URL 结束时采取另一个并检查...等等,或者找到一些有效的 URL。所有这些事情都必须在 AVPlayer 尝试播放声音之前完成。
如何实施以及在哪里实施?
请用简单的语言讲述和描述解决方案,因为我是快速和多线程的初学者。
我会使用该AVPlayerItem.Status属性来查看它何时失败。在当前代码中,您在创建项目后立即检查状态,这将始终产生与默认情况下AVPlayerItem初始化时相同的结果。statusunknown
AVPlayerItem一旦您与玩家关联,它们就会排队。为了能够跟踪状态变化,您需要设置一个观察者。
文档https://developer.apple.com/documentation/avfoundation/avplayeritem仍然建议使用“旧式”,addObserver但根据您的偏好,我会选择较新的块式。
// 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
}
})
Run Code Online (Sandbox Code Playgroud)
您也可以在实例上设置类似的观察者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()
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4122 次 |
| 最近记录: |