简体   繁体   中英

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

I am a swift beginner currently working on my first iOS app.

I have a TableViewController which has several cells and each cell contains a play button. 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!

The problem is that every single cell has its own independent player. You want just one player, so that you can stop it and start a new sound. For example, make the one player a property of the view controller. Every cell can see it but there is just one.

create an extension for AVPlayer because AVPlayer does not own condition for playing. extension given below.

extension AVPlayer {
    var isPlaying: Bool {
        return rate != 0 && error == nil
    }
}

use it while tap on play like this.

if player?.isPlaying == true {
   player?.pause()
   player?.seek(to: CMTime(seconds: 0, preferredTimescale: 60))
}
//set up you audio file to player
player?.play()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM