NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

AVAudioPlayerDelegate SwiftUI

Forums > SwiftUI

Working with iPadOS 14 Beta 3.

import Foundation
import SwiftUI
import AVFoundation

class AudioHandler: NSObject, ObservableObject, AVAudioPlayerDelegate {

    @Published var isPlaying: Bool = false {
        willSet {
            if newValue == true {
                playAudio()
            }
        }
    }

    var myAudioPlayer = AVAudioPlayer()
    var fileName = ""

    override init() {
        super.init()
        myAudioPlayer.delegate = self
    }

    func playAudio() {
        let path = Bundle.main.path(forResource: fileName, ofType:nil)!
        let url = URL(fileURLWithPath: path)

        do {
            myAudioPlayer = try AVAudioPlayer(contentsOf: url)
            myAudioPlayer.play()
        } catch {
            // couldn't load file :(
        }
    }

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        print("Did finish Playing")
        isPlaying = false
    }
}

Usage

if audioHandler.isPlaying == false {

                            Button(action: {
                                audioHandler.fileName = event.fileName
                                audioHandler.isPlaying.toggle()

                                print("Button Tapped")
                            }) {
                                Image(systemName: "play.circle")
                                    .font(.largeTitle)
                                    .foregroundColor(Color.white)
                            }
                        }

Click on the button, it plays the audio file. The audioPlayerDidFinishPlaying is never called. Tested on the device. I have a similar class for SpeechSythesis, and the (speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance)) works fine. Is something up with AVAudioPlayerDelegate, or am I doing something wrong?

1      

Just in case you've not got this working yet, all you need to do is move the delegate assignment out of the initialiser until after myAudioPlayer is instantiated.

So :-

override init() {
        super.init()
        // not here: myAudioPlayer.delegate = self
    }

func playAudio() {
        let path = Bundle.main.path(forResource: fileName, ofType:nil)!
        let url = URL(fileURLWithPath: path)

        do {
            myAudioPlayer = try AVAudioPlayer(contentsOf: url)
            myAudioPlayer.delegate = self    // Add here (once myAudioPlayer is instantiated)
            myAudioPlayer.play()
        } catch {
            // couldn't load file :(
        }
    }

Apologies if there's a better way of assigning the delegate but this worked for me. G

1      

Hacking with Swift is sponsored by Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.