gpt4 book ai didi

ios - 自定义 TableViewController 在 Swift 3 中播放声音和崩溃

转载 作者:行者123 更新时间:2023-11-30 12:18:33 25 4
gpt4 key购买 nike

我正在 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.
}
}

最佳答案

  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")
    }

关于ios - 自定义 TableViewController 在 Swift 3 中播放声音和崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45099541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com