[英]Swift - How to stop currently playing audio automatically when another play button in different UITableView cells are pressed?
I am a swift beginner currently working on my first iOS app. 我是一位敏捷的初学者,目前正在开发我的第一个iOS应用程序。
I have a TableViewController
which has several cells and each cell contains a play button. 我有一个TableViewController
,其中有几个单元格,每个单元格都包含一个播放按钮。 When a few play buttons are pressed, a few different audios are played at the same time, but I would like to stop a currently playing audio when another playing play button is pressed. 当按下几个播放按钮时,会同时播放几个不同的音频,但是我想在按下另一个正在播放的播放按钮时停止当前正在播放的音频。
Here are the sample codes I created. 这是我创建的示例代码。
Please give me an advice. 请给我一个建议。 Thank you so much! 非常感谢!
ViewController.swift 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 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
}
}
}
One possible solution is to create _currentActivePlayer object variable. 一种可能的解决方案是创建_currentActivePlayer对象变量。 When you start playing audio then assign to it playing player. 当您开始播放音频时,然后分配给它播放播放器。 When other cell wants to play audio then check that variable, stop the player and assign new playing player. 当其他单元要播放音频时,请检查该变量,停止播放器并分配新的播放器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.