自定义 TableViewController 声音在 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.
} 
}
  1. 您必须在viewDidLoad中初始化players

    players = Array(repeating: nil, count: audioFileNames.count)
    
  2. 在使用之前,您必须检查播放器启动

    if players[indexPath.row] == nil {
    players[indexPath.row] = setupAudioPlayerWithFile(file: self.audioFileNames[indexPath.row]! as String,  type: "mp3")    
    }
    

我已经尝试过了,它不适用于播放器数组。您需要一次播放一个。

很确定这是 swift 的某种错误行为 我发现如果你像这样初始化:

var player: AVAudioPlayer? = nil

它会更好;每次你提到它时,添加一个"?"。 例如:

player?.play()

未设置 URL 时,它将停止崩溃。 在某些情况下,这确实是必要的,并且没有其他明显的替代方案。

如果有人找到更好的解决方案,请告诉我!

最新更新