2017-07-14 60 views
0

我與音頻的陣列工作在斯威夫特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. 
    } 
} 
+0

問題是'players = [setupAudioPlayerWithFile(file:self.audioFileNames [indexPath.row]!as String,type:「mp3」)!]'。 – Codus

+0

你不需要創建audioplayer陣列使用只有一個音頻播放器,只需停下來,然後開始,一旦你點擊tableview單元格 –

回答

0
  1. 必須在viewDidLoad

    players = Array(repeating: nil, count: audioFileNames.count) 
    
  2. 您使用它之前,你必須檢查球員開始初始化players

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

我已經試過這樣做,它不起作用球員陣列。您需要一次播放一個。

0

肯定它的某種雨燕 的錯誤行爲,我發現,如果你初始化像這樣:

var player: AVAudioPlayer? = nil 

會更好;每次你提到它的時候,添加一個「?」它 例如:

player?.play() 

它將停止時未設置URL崩潰。 有些情況下,這確實是必要的,沒有其他明顯的選擇。

如果有人找到更好的解決方案,請讓我知道!