AVFAudio in Swift
In this blog, we are going to learn about the AVFAudio framework in swift. AVFAudio is a framework that helps in play, record, and process audio files in swift. In every other app, we need to audio-video support like watching video and listening to music or audiobook.
Please follow the below steps to integrate the AVFAudio framework into your iOS project.
Step – 1
In this step, Create a project and create three buttons for play, stop and repeat audio player.
Step – 2
Import the AVFoundation framework in your project
import AVFoundation
Step – 3
Now we will create a player from AVAudioPlayer class and outlet for the play, stop and repeat button and also create a variable for determining the repeat state
1 2 3 4 5 6 |
var player = AVAudioPlayer() var repeatAudio = false @IBOutlet weak var repeatBtn: UIButton! @IBOutlet weak var playBtn: UIButton! @IBOutlet weak var stopBtn: UIButton! |
Step – 4
Now create a function for the tap of the Play Button and also the required URL from the audio file, after that handle the URL and assign delegates for the player.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
@IBAction func playBtnTapped(_ sender: UIButton) { let requiredUrl = NSURL(fileURLWithPath: Bundle.main.path(forResource: "peacok_ring", ofType: "wav")!) do { player = try AVAudioPlayer(contentsOf: requiredUrl as URL) player.delegate = self if(player.prepareToPlay()) { player.play() } }catch { print(error.localizedDescription) } } |
Step – 5
After that, we will create the stop and repeat button function in your project.
1 2 3 4 5 6 7 8 9 10 |
@IBAction func repeatBtnTapped(_ sender: UIButton) { repeatAudio = !repeatAudio //repeatAudio = true } @IBAction func stopBtnTapped(_ sender: UIButton) { player.stop() } |
Step – 6
However, we will use AVAudioPlayerDelegate for using delegates of player.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
extension ViewController: AVAudioPlayerDelegate { func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { if repeatAudio { player.play() } // Audio Played Successfully } func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) { // Show Alert unable to play Audio guard let error = error else { return } let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert) //handler: nil) let okAction = UIAlertAction(title: "Ok", style: .default) { (action) in self.dismiss(animated: true, completion: nil) } alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } } |
Conclusion
We have integrated the audio player into our iOS App. For more information, please refer to the apple officials documentation from here.
Thanks for reading my blog. Please refer to my other blog from here.