简体   繁体   中英

How to automatically change background image of a button after audio stops playing in swift?

I'm working on a voice record app using xcode 10.2.1 ... After recording an audio, the audio is displayed in a tableview. Inside each cell I have a play button that when pressed should switch to pause. After audio finishes it should get back to play. How can I achieve this in swift?

I've tried many answers on stack but none of them met my requirements.

func btnPlayPressed(index: Int) {
        let audio = self.audios[index]

        if audio.isPlaying {
            AudioManager.sharedInstance.stopSound()
            self.audios[index].isPlaying = false
        } else {
            AudioManager.sharedInstance.playSound(fileName: audio.fileName)
            self.audios[index].isPlaying = true
        }
    }

You should use NSNotificationCenter and listen when the audio finished playing. In that function you must be changing the image of the button. Are you using AVPlayer ?

you can extend AVAudioPlayerDelegate and override the function below. Then this function triggers you understand that audio finished.

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    print("Finish")
}

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