Swift - 当不同的UITableView单元中的另一个播放按钮被按下时,如何自动停止当前正在播放的音频?
问题描述:
我是一位快速入门者,目前正在开发我的第一款iOS应用程序。Swift - 当不同的UITableView单元中的另一个播放按钮被按下时,如何自动停止当前正在播放的音频?
我有一个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对象变量。当你开始播放音频,然后分配给它播放播放器。当其他单元想播放音频时,检查该变量,停止播放器并分配新的播放器。
谢谢您的回复!我试图创建一个像你在ViewController.swift中建议的对象,但我有一个检测表视图单元格中按下哪个播放按钮的问题。我不确定我是否在正确的道路上。你能否给我更多的线索?先谢谢你。 – coonie
Stackoverflow上有很多问题如何在按钮处理程序中获取相应的单元格。我不想复制答案,只需找到解决方案。 – kirander
好的。谢谢! – coonie