AudioPlayer.swift (1422B)
1 // 2 // AudioPlayer.swift 3 // captainsLog 4 // 5 // Created by Benjamin Welner on 10/30/19. 6 // Copyright © 2019 FIGBERT Industries. All rights reserved. 7 // 8 9 import Foundation 10 import SwiftUI 11 import Combine 12 import AVFoundation 13 14 class AudioPlayer: NSObject, ObservableObject, AVAudioPlayerDelegate { 15 16 @Published var audioPlayer: AVAudioPlayer! 17 @Published var isPlaying = false 18 @Published var hasPlayed = false 19 20 func startPlayback(audio: URL) { 21 if (!hasPlayed) { 22 let playbackSession = AVAudioSession.sharedInstance() 23 do { 24 try playbackSession.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker) 25 } catch { 26 print("Playing over the devices speakers failed") 27 } 28 do { 29 audioPlayer = try AVAudioPlayer(contentsOf: audio) 30 audioPlayer.delegate = self 31 audioPlayer.play() 32 isPlaying = true 33 hasPlayed = true 34 } catch { 35 print("Playback failed") 36 } 37 } else { 38 audioPlayer.play() 39 isPlaying = true 40 } 41 } 42 43 func pausePlayback() { 44 audioPlayer.pause() 45 isPlaying = false 46 } 47 48 func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { 49 if flag { 50 isPlaying = false 51 } 52 } 53 }