1
私は現在、私の最初の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
}
}
}
ありがとうございました。 ViewController.swiftで提案したようなオブジェクトを作成しようとしましたが、テーブルビューのセルで再生ボタンが押されたことを検出するという問題があります。私が正しい道にいるかどうかはわかりません。もっと手がかりをくれてくれませんか?前もって感謝します。 – coonie
ボタンハンドラで対応するセルを取得する方法は、Stackoverflowに多くの質問があります。私は答えを複製したくない、解決策を見つけるだけだ。 – kirander
ありがとうございました! – coonie