AVAudioPlayer完成播放时切换tableview单元格图像

时间:2016-08-05 01:12:34

标签: ios swift avaudioplayer tableviewcell

我有一个tableview,每个单元格都有一个播放按钮。播放按钮是UIButton,可在播放和暂停图像之间切换。按下播放/暂停按钮时,AVAudioPlayer播放/暂停与该单元格关联的音频文件。截至目前,我的图像完美切换并与音频播放器同步。但是,当音频播放完毕后,我希望图像切换回默认状态 - 播放按钮图像。

//View controller containing tableview
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = self.audioTable.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! AudioCell

    let track = self.sectionTracks[indexPath.row]

    cell.playButton.addTarget(self, action: #selector(HomeController.playPausePressed(_:)), forControlEvents: UIControlEvents.TouchUpInside)

    var playButtonImage = UIImage(named: "TableViewCellPlayButton84.jpg")
    var pauseButtonImage = UIImage(named: "TableViewCellPauseButton84.jpg")
    playButtonImage = playButtonImage?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
    pauseButtonImage = pauseButtonImage?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)

    cell.playButton.setImage(playButtonImage, forState: UIControlState.Normal)
    cell.playButton.setImage(pauseButtonImage, forState: UIControlState.Selected)
    cell.playButton.selected = false

    return cell
}

func playPausePressed(sender:UIButton) {

    let pointInTable: CGPoint = sender.convertPoint(sender.bounds.origin, toView: self.audioTable)
    let cellIndexPath = self.audioTable.indexPathForRowAtPoint(pointInTable)
    let track = self.sectionTracks[cellIndexPath!.row]

     //Handle AVAudioPlayer play/pause functionality
}

//Custom tableview cell file
@IBAction func playPausePressed(sender: UIButton!) {

    if (sender.selected)
    {
        sender.selected = false
    }
    else{
        sender.selected = true
    }
}

1 个答案:

答案 0 :(得分:0)

您可以订阅成为AVAudioPlayer的代表,然后检查音频何时完成。你可以一次播放多个文件吗?如果您可以播放多个,则必须跟踪所有播放的音频,然后根据代理被触发的时间以及播放器与哪个行相关联来切换行上的按钮。如果您只能播放一个,那么当用户开始播放音频时,只需保存该行,当音频结束时切换该行的按钮。

https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVAudioPlayerDelegateProtocolReference/

Case "(result1)", "(result2)", "(result3)"

如上所述进行扩展以将名称存储到AVAudioPlayer实例可能会有所帮助。然后,您可以在可变字典中跟踪正在播放的音频的名称和单元格的索引路径。当您收到委托函数private var xoAssociationKey: UInt8 = 0 extension AVAudioPlayer { var name: String! { get { return objc_getAssociatedObject(self, &xoAssociationKey) as? String } set(newValue) { objc_setAssociatedObject(self, &xoAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } } 的回调时,您可以在字典中查找optional func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool),它将返回该按钮单元格的索引路径。从表格视图中获取单元格,然后切换按钮选择状态。

修改

对于一次播放的单个单元格,您可以将变量添加到类player.name

当音频开始播放时,将其设置为单击按钮的单元格索引路径。

然后在播放完成事件中,只需抓住单元格并切换按钮

var playingAudioIndexPath:NSIndexPath?

DMCApps