【问题标题】:Custom TableViewController sounds play and crash in Swift 3自定义 TableViewController 声音在 Swift 3 中播放和崩溃
【发布时间】: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


【解决方案1】:
  1. 你必须在viewDidLoad中初始化players

    players = Array(repeating: nil, count: audioFileNames.count)
    
  2. 您必须在使用前检查播放器是否已启动

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

【讨论】:

    【解决方案2】:

    我已经尝试过了,但它不适用于一系列玩家。您需要一次播放一个。

    【讨论】:

      【解决方案3】:

      很确定这是 swift 的某种错误行为 我发现如果你这样初始化:

      var player: AVAudioPlayer? = nil
      

      会更好;每次引用它时,添加一个“?”给它 例如:

      player?.play()
      

      当没有设置 URL 时它将停止崩溃。 在某些情况下,这确实是必要的,并且没有其他明显的替代方案。

      如果有人找到更好的解决方案,请告诉我!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-28
        • 1970-01-01
        • 2019-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多