我与音频的阵列工作在斯威夫特3.定制TableViewController声音播放和崩溃斯威夫特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”)!]'。 – Codus
你不需要创建audioplayer阵列使用只有一个音频播放器,只需停下来,然后开始,一旦你点击tableview单元格 –