WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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      

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.