TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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 Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your 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.