簡體   English   中英

Swift-如何在按下不同UITableView單元格中的另一個播放按鈕時自動停止當前播放音頻?

[英]Swift - How to stop currently playing audio automatically when another play button in different UITableView cells are pressed?

我是一位敏捷的初學者,目前正在開發我的第一個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對象變量。 當您開始播放音頻時,然后分配給它播放播放器。 當其他單元要播放音頻時,請檢查該變量,停止播放器並分配新的播放器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM