UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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?

2      

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

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot 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.