gpt4 book ai didi

ios - Swift - 如何在按下不同 UITableView 单元格中的另一个播放按钮时自动停止当前播放的音频?

转载 作者:行者123 更新时间:2023-11-28 07:58:10 25 4
gpt4 key购买 nike

我是一个快速的初学者,目前正在开发我的第一个 iOS 应用程序。

我有一个 TableViewController,它有几个单元格,每个单元格都包含一个播放按钮。当按下几个播放按钮时,同时播放几个不同的音频,但我想在按下另一个播放按钮时停止当前正在播放的音频。

这是我创建的示例代码。

请给我一个建议。非常感谢!

ViewController.swift

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
super.viewDidLoad()

tableView.delegate = self
tableView.dataSource = self

tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "cell")

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 88
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
return cell
}


}

TableViewCell.swift

import UIKit
import AVFoundation

class TableViewCell: UITableViewCell, AVAudioPlayerDelegate {

var audioPlayer: AVAudioPlayer = AVAudioPlayer()
var counter = 0

@IBAction func buttonTapped(_ sender: Any) {

// Audio player setting
do {

audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "sample", ofType: "mp3")!))
audioPlayer.delegate = self
audioPlayer.prepareToPlay()

} catch {
print(error)
}

if counter == 0 {
audioPlayer.play()
counter = 1
} else {
audioPlayer.stop()
counter = 0
}
}

}

最佳答案

一个可能的解决方案是创建 _currentActivePlayer 对象变量。当您开始播放音频时,然后分配给它播放播放器。当其他单元格想要播放音频时,检查该变量,停止播放器并分配新的播放器。

关于ios - Swift - 如何在按下不同 UITableView 单元格中的另一个播放按钮时自动停止当前播放的音频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47365780/

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