Volume View iOS Tutorial

When using audio in your app sometimes you want the user to change the volume. With the help of the MPVolumeView object you create a builtin Volume control which also has the abilty  to redirect the output to an airplay device. In this tutorial we will play a sound and display the volume controls. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOSVolumeViewTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Some audio is needed to play, so download the music file and add it to the Assets library.

Go to the Storyboard and drag two Buttons next to each other to the main view. Set the title of the left button to Play and the right button to Stop. Select the Resolve Auto Layout Issues button and select Reset to Suggested Constraints.

The Storyboard should look like this.

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Play Button to the ViewController class and create the following Action

Ctrl and drag from the Stop Button to the ViewController class and create the following Action

The AVFoundation framework is needed for playing the music file and the MediaPlayer framework to use the MPVolumeView. Go to the ViewController.swift file and import the frameworks

import AVFoundation
import MediaPlayer

Inside the ViewController class add the following properties

var audioPlayer = AVAudioPlayer()
let wrapperView = UIView(frame: CGRect(x: 30, y: 200, width: 300, height: 20))

Implement the viewDidLoad method

override func viewDidLoad() {
    super.viewDidLoad()

    // 1
    if let asset = NSDataAsset(name: "amorphis-my-enemy") {

        // 2
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback)
            try AVAudioSession.sharedInstance().setActive(true)
            try audioPlayer = AVAudioPlayer(data:asset.data, fileTypeHint:"mp3")
            audioPlayer.prepareToPlay()
        } catch {
            print("error")
        }
    }
}
  1. The audio file is loaded from the Assets library.

  2. The audio session category is set to playback and set to active.

Implement the playSound method

@IBAction func playSound(_ sender: Any) {
    // 1
    audioPlayer.play()
        
    // 2
    view.backgroundColor = UIColor.clear
    view.addSubview(wrapperView)
        
    // 3
    let volumeView = MPVolumeView(frame: wrapperView.bounds)
    wrapperView.addSubview(volumeView)
}
  1. The audio file starts to play

  2. The wrapper view is added as a subview to the main view

  3. The MPVolumeView is added as a subview of the wrapper view.

Implement the stopSound method.

@IBAction func stopSound(_ sender: Any) {
    audioPlayer.stop()
    wrapperView.removeFromSuperview()
}

The audio is stopped and the wrapperView including the volume view is removed from the superview.

Build and Run the project, select the play button and change the volume and Output source. Note this can only be run on an actual device, since in the iOS Simulator you will only see a black view.

You can download the source code of the IOSVolumeViewTutorialat the ioscreator repository on Github.