[英]Custom TableViewController sounds play and crash in Swift 3
我正在Swift 3中處理音頻數組。
import Foundation
import UIKit
import AVFoundation
class TableViewController: UITableViewController, AVAudioPlayerDelegate {
var players: [AVAudioPlayer] = []
var audioFileNames = [String?]()
override func viewDidLoad() {
audioFileNames = [ "ɔɪ", "eə", "aʊ", "eɪ"]
}
我將單個聲音顯示在自定義單元中。 如果我按下一個單元格,則會播放聲音,但是當我按下另一個單元格時,應用程序將凍結並崩潰。
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.audioFileNames.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell")! as UITableViewCell
cell.textLabel?.text = self.audioFileNames[indexPath.row]
return cell
}
該代碼在此功能處中斷。
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
players = [setupAudioPlayerWithFile(file: self.audioFileNames[indexPath.row]! as String, type: "mp3")!]
players[indexPath.row].play()
}
func setupAudioPlayerWithFile(file: String, type: String) -> AVAudioPlayer? {
let path = Bundle.main.path(forResource: file as String, ofType: type as String)
let url = NSURL.fileURL(withPath: path!)
var audioPlayer:AVAudioPlayer?
do {
try audioPlayer = AVAudioPlayer(contentsOf: url)
} catch {
print("Player not available")
}
return audioPlayer
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
您必須在viewDidLoad
初始化players
players = Array(repeating: nil, count: audioFileNames.count)
您必須先檢查播放器啟動后再使用
if players[indexPath.row] == nil { players[indexPath.row] = setupAudioPlayerWithFile(file: self.audioFileNames[indexPath.row]! as String, type: "mp3") }
我已經嘗試過了,但不適用於一系列玩家。 您需要一次播放一個。
可以肯定,這是一種迅速的越野車行為,我發現如果您這樣初始化:
var player: AVAudioPlayer? = nil
會好起來的; 並在每次引用它時都添加一個“ ?
”,例如:
player?.play()
如果未設置網址,它將停止崩潰。 在某些情況下,這確實是必要的,沒有其他明顯的選擇。
如果有人找到更好的解決方案,請告訴我!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.