How to play a sound using Swift?


In Swift, there is a framework called AVFoundation that provides flexibility to play audio files. This framework provides you with a class called AVAudioPlayer to manage audio play and pause. In this article, you will learn how to play a sound using the AVAudioPlayer class in Swift.

AVFoundation

This framework is a very powerful multimedia framework in Swift. This provides you with most of the features to work with media files like audio, video, and other types of media files. This framework uses some common classes to manage media files.

  • AVPlayer − This is a class that supports high-quality audio and video playback. It can play local or remote media files and has controls for stopping, seeking, and volume adjustment.

  • AVAudioPlayer − This is an AVPlayer subclass that is designed specifically to play audio files. It has other capabilities like adjusting the number of loops, modifying the playback rate, and adjusting the loudness.

  • AVCaptureSession − This class is used to capture media material from input devices such as cameras and microphones. It can record video and audio, and it has options for altering the exposure, focus, and other capture settings.

  • AVAsset − This is a class that represents a media asset, such as a video or audio file. It offers asset metadata like as duration and format and may be used to extract individual frames or portions of video material.

  • AVMetadata − This is a class for working with media asset metadata such as title, artist, and album information. It can read and write metadata and provides a defined set of keys for commonly used metadata fields.

  • AVPlayerLayer − A layer subclass capable of displaying video material from an AVPlayer instance. It allows you to integrate video playback into your program's user interface and gives options for modifying the aspect ratio and other display parameters.

These are only a few of the AVFoundation framework's most valuable classes and functionalities. With Swift, there are several different classes and APIs for interacting with media assets, including support for real-time audio processing, video editing, and more.

The AVAudioPlayer class is a subclass of the AVPlayer class in the AVFoundation framework, which provides a simple interface for playing audio content in your Swift application. Here are some of the key properties and methods of the AVAudioPlayer class −

Properties

  • currentTime − This property returns the current playback time of the audio file, in seconds.

  • duration − This property returns the audio file duration, in seconds.

  • volume − This property sets the volume of the audio playback, with a range of 0.0 (silent) to 1.0 (maximum volume).

  • numberOfLoops − This property sets the number of times the audio file should be played before stopping. A value of -1 means the audio file should loop indefinitely.

  • isPlaying − This property returns a boolean value indicating whether the audio file is currently playing.

Methods

  • init(contentsOf url: URL) − This is the designated initializer for the AVAudioPlayer class, which takes a URL for the audio file to be played.

  • play() − This method starts playback of the audio file.

  • pause() − This method pauses audio file playback.

  • stop() − This method stops the audio file playback.

  • prepareToPlay() − This method prepares the audio player for playback, by loading the audio file into memory and performing any necessary initialization.

  • setVolume(_ volume: Float, fadeDuration: TimeInterval) − This method sets the audio player's volume, with an optional fade-in or fade-out duration.

  • currentTime (setter) − This method sets the current playback time of the audio file, in seconds.

  • numberOfLoops (setter) − This method sets the number of times the audio file should be played before stopping.

Here is an Example of How to Play and Pause a Sound

  • Step 1 − First, add an audio file to your project directory. In this example, we added an audio file named "sample_audio.mp3" to the local directory.

  • Step 2 − In order to play an audio file in Swift, you need to import the AVFoundation framework.

  • Step 3 − Now, we declare a property like "var audioPlayer: AVAudioPlayer?" to play an audio file.

  • Step 4 − You can initialize an object of AVAudioPlayer class. You can use the AVAudioPlayer(contentsOf: URL) initializer by providing the local URL of the audio file.

  • Step 5 − To play and pause an audio file from a URL, you need to call the methods "play" and "pause" to pause an ongoing audio file.

Example

import UIKit
import AVFoundation
class TestController: UIViewController {
    
   private var audioPlayer: AVAudioPlayer?    
   private lazy var playButton: UIButton = {
      let button = UIButton()
      button.backgroundColor = .darkGray
      button.setTitle("Play Sound", for: .normal)
      button.setTitleColor(.white, for: .normal)
      button.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: .medium)
      button.layer.cornerRadius = 10
      button.clipsToBounds = true
      button.addTarget(self, action: #selector(handleButtonTapped), for: .touchUpInside)
      button.translatesAutoresizingMaskIntoConstraints = false
      return button
   }()
    
   override func viewDidLoad() {
      super.viewDidLoad()
      initialSetup() 
   }
    
   override func viewDidAppear(_ animated: Bool) {
      super.viewDidAppear(animated)
   }   
   private func initialSetup() {        
      view.backgroundColor = .white
      navigationItem.title = "Play Sound"
        
      view.addSubview(playButton)
        
      playButton.heightAnchor.constraint(equalToConstant: 45).isActive = true
      playButton.widthAnchor.constraint(equalToConstant: 250).isActive = true
      playButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
      playButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
   }    
   @objc private func handleButtonTapped() {
      if audioPlayer != nil && audioPlayer!.isPlaying {
         audioPlayer?.pause()
         playButton.setTitle("Play Sound", for: .normal)
      } else {
         guard let path = Bundle.main.path(forResource: "sample_audio", ofType:"mp3") else {
         return }
         let url = URL(fileURLWithPath: path)
            
         do {               
            if audioPlayer == nil {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            }               
            audioPlayer?.play()
            playButton.setTitle("Pause Sound", for: .normal)
         } catch let error {
            print(error.localizedDescription)
         }
      }
   }
}

Output

Conclusion

You can import the AVFoundation framework in order to use the AVAudioPlayer class. This class provides you the functionality to play and pause an audio file. This class provides other properties and methods to manage execution.

Updated on: 24-Apr-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements