2017-07-14 59 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崩溃。 有些情况下,这确实是必要的,没有其他明显的选择。

如果有人找到更好的解决方案,请让我知道!