2017-11-18 159 views
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 
    } 
} 

} 

回答

0

一種可能的解決方案是創建_currentActivePlayer對象變量。當你開始播放音頻,然後分配給它播放播放器。當其他單元想播放音頻時,檢查該變量,停止播放器並分配新的播放器。

+0

謝謝您的回覆!我試圖創建一個像你在ViewController.swift中建議的對象,但我有一個檢測表視圖單元格中按下哪個播放按鈕的問題。我不確定我是否在正確的道路上。你能否給我更多的線索?先謝謝你。 – coonie

+0

Stackoverflow上有很多問題如何在按鈕處理程序中獲取相應的單元格。我不想複製答案,只需找到解決方案。 – kirander

+0

好的。謝謝! – coonie

相關問題