我與音頻的陣列工作在斯威夫特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單元格 –