Play audio file in SwiftUI

You can play audio files in SwiftUI in the same manner you do it in Swift and that is with the help of AVFoundation framework.

AVFoundation framework works with audio-visual assets and it provides App the capability to interact with the hardware. So in this tutorial, we’ll see how we can use this framework to play audio files.

What this blog will cover:

  • AVFondation Framework
  • onAppear method
  • try and catch block

Importing AVFoundation:

We’ll start with importing the AVFoundation framework and for doing so just put this line at the top of your SwiftUI file.

import AVFoundation

Importing Audio File in SwiftUI

Now for importing audio files, Go to your project navigator on the right-side panel of XCode. There Create a new folder inside your project folder and name it “Sound” then drag and drop your audio file into the sound folder. And don’t forget to click on the “copy if needed” checkbox.

SwiftUI play audio

Using AVFoundation for playing Audio in SwiftUI 

Declare the property audioPlayer of type AVAudioPlayer which we get from the AVfoundation. We’ll initialize it later in playSound function.

     var audioPlayer : AVAudioPlayer?

 

So, Now create the function playSound, and in this function, we’ll grab the file which we want to play and for doing that we’ll be needing that audio file path, the path is where the audio resource file is located in the project.

 func playSound(){
      
        //getting the resource path
        let resourcePath = Bundle.main.url(forResource: "windChime", withExtension: "mp3")
     
}
  • Bundle.main.url will give you the path of the audio file that you’ve just imported. You’ll give that path to the AVAudioPlayer which is the audio player and it will fetch your audio file from that path and play it for you.
  • In the forResource parameter, we have to give the name of our audio file and in the withExtension parameter, We have to mention the extension of the audio file like mp3, wav, etc.

Also read: How to play an MP3 File in Swift Storyboard

now all we have to do is initialize AVAudioPlayer with the resource path and call its play function.

The play function of the AVAudioPlayer will play your audio file.

               audioPlayer?.play()

likewise, the stop function will stop the audio.

             audioPlayer?.stop()

         

func playSound(){
     
       //getting the resource path
       let resourcePath = Bundle.main.url(forResource: "windChime", withExtension: "mp3")
       
       do{
           //initializing the audio player with the resource path
           audioPlayer = try AVAudioPlayer(contentsOf: resourcePath!)
           
           //play the audio
           audioPlayer?.play()

          //stop the audio
         // audioPlayer?.stop()
          
    
       }
       catch{
         //error handling
           print(error.localizedDescription)
       }
   }
  • try and catch block helps us to handle the error and prevents the app from crashing

Calling the playSound function in the main View.

struct ContentView: View {
    var body: some View {
     
        VStack{
          
            Text("Wind Chime is playing").fontWeight(.heavy)
        }
        .onAppear(perform: self.playSound)
       
    }
    
    func playSound(){
      
        //getting the resource path
        let resourcePath = Bundle.main.url(forResource: "windChime", withExtension: "mp3")
        
        do{
            //initializing audio player with the resource path
            audioPlayer = try AVAudioPlayer(contentsOf: resourcePath!)
            
            //play the audio
         //   audioPlayer?.play()
            
            //stop the audio
            // audioPlayer?.stop()
            
        }
        catch{
          //error handling
            print(error.localizedDescription)
        }
    }

}
  • onAppear is the function that performs an action when the view appears. so this onAppear method will call the playSound method, which will play the audio file, just when the view appears on the screen.

 

Complete Code for reference:

//
//  ContentView.swift
//  MyAudioPlayerApp
//
//  Created by test on 4/18/23.
//

import SwiftUI
import AVFoundation

var audioPlayer : AVAudioPlayer?

struct ContentView: View {
    var body: some View {
     
        VStack{
          
            Text("Wind Chime is playing").fontWeight(.heavy)
        }
        .onAppear(perform: self.playSound)
       
    }
    
    func playSound(){
      
        //getting the resource path
        let resourcePath = Bundle.main.url(forResource: "windChime", withExtension: "mp3")
        
        do{
            //initializing audio player with the resource path
            audioPlayer = try AVAudioPlayer(contentsOf: resourcePath!)
            
            //play the audio
         //   audioPlayer?.play()
            
            //stop the audio
            // audioPlayer?.stop()
            
        }
        catch{
          //error handling
            print(error.localizedDescription)
        }
    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *