【发布时间】:2017-07-14 09:34:18
【问题描述】:
我正在使用 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.
}
}
【问题讨论】:
-
问题是
players = [setupAudioPlayerWithFile(file: self.audioFileNames[indexPath.row]! as String, type: "mp3")!]。 -
您不需要创建音频播放器数组,只使用一个音频播放器,只需单击 tableview 单元格即可停止和启动
标签: ios swift uitableview swift3 avplayer