AVPlayer. Play Music MP3 File From a Remote URL In Swift

In this tutorial, you will learn how to play the music mp3 file from a remote URL in Swift. To play music in your mobile app, you will use two very important classes: AVPlayer and AVPlayerItem. But before I show you how to use them, I will briefly describe each one to you.

  • AVPlayer is a class that provides the interface to control the playback and timing of a media asset, such as an MP3 file. You can use an instance of AVPlayer to play local and remote file-based media, as well as audiovisual media served using HTTP Live Streaming. To create an AVPlayer instance, you need to pass an AVPlayerItem object as an argument.
  • AVPlayerItem is a class that models the timing and presentation state of an asset during playback. You can create an AVPlayerItem object with a URL pointing to the media to play, and it will automatically create an AVAsset object internally. Alternatively, you can create an AVPlayerItem object with an AVAsset object that you create explicitly. You can access the AVAsset object of an AVPlayerItem through its asset property.

Step 1: Create AVPlayer and AVPlayerItem

At first, you need to create an instance of AVPlayer and AVPlayerItemAVPlayer is a class that you use to play media and AVPlayerItem represents a single media item.

let url = URL(string: "https://s3.amazonaws.com/kargopolov/kukushka.mp3")
let playerItem:AVPlayerItem = AVPlayerItem(url: url!)
player = AVPlayer(playerItem: playerItem)

Step 2: Create UIButton programmatically

Next, you need to create a UIButton programmatically. We set the button’s type, frame, title, and add a target-action for the .touchUpInside event.

For UIKit, use the following code:

playButton = UIButton(type: UIButton.ButtonType.system) as UIButton
let xPostion:CGFloat =  50
let yPostion:CGFloat =  100
let buttonWidth:CGFloat =  150
let buttonHeight:CGFloat =  45
playButton!.frame = CGRect(x: xPostion, y: yPostion, width: buttonWidth, height: buttonHeight)
playButton!.center = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
playButton!.backgroundColor = UIColor.lightGray
playButton!.setTitle("Play", for: UIControl.State.normal)
playButton!.tintColor = UIColor.black
playButton!.addTarget(self, action: #selector(self.playButtonTapped(_:)), for: .touchUpInside)
self.view.addSubview(playButton!)

For SwiftUI, use the following code:

Button(action: {
    self.playButtonTapped()
}) {
    Text(playButtonTitle)
        .foregroundColor(.black)
        .padding()
        .background(Color.gray)
        .cornerRadius(10)
}
.padding()

Step 3: Create AVPlayerLayer and add it as a subview

Next, you can create an AVPlayerLayer and add it as a subview. AVPlayerLayer is a layer that you use to display the visual content of an AVPlayer object.

For UIKit, use the following code:

let playerLayer=AVPlayerLayer(player: player!)
playerLayer.frame=CGRect(x:0, y:0, width:10, height:50)
self.view.layer.addSublayer(playerLayer)

For SwiftUI, use the following code:

playerLayer = AVPlayerLayer(player: player!)
playerLayer?.frame = CGRect(x:   0, y:   0, width:   10, height:   50)

Step 4: Handle the Play button action to Pause and Play Music

In this step, you handle the action of the play button to pause and play the music. Check if the player is currently playing, and if it is, pause it, otherwise, play it.

For UIKit, use the following code:

@objc func playButtonTapped(_ sender:UIButton)
{
    if player?.rate ==  0
    {
        player!.play()
        playButton!.setTitle("Pause", for: UIControl.State.normal)
    } else {
        player!.pause()
        playButton!.setTitle("Play", for: UIControl.State.normal)
    }
}

For SwiftUI, use the following code:

func playButtonTapped() {
    if player?.rate ==   0 {
        player?.play()
        playButtonTitle = "Pause"
    } else {
        player?.pause()
        playButtonTitle = "Play"
    }
}

Step 5: Set UIImage on the Play button if needed

To set a UIImage on the Play button if needed. However, in the provided complete code example, you are not setting any image on the play button. But you can do it like the below code example:

@objc func playButtonTapped(_ sender:UIButton)
    {
        if player?.rate == 0
        {
            player!.play()
            playButton!.setImage(UIImage(named: "player_control_pause_50px.png"), forState: UIControlState.Normal)
        } else {
            player!.pause()
            playButton!.setImage(UIImage(named: "player_control_play_50px.png"), forState: UIControlState.Normal)
        }
    }

Complete Code Example UIKit

Here is the complete code example with all the steps combined using UIKit:

import UIKit
import AVFoundation

class ViewController: UIViewController  {
    
    var player:AVPlayer?
    var playerItem:AVPlayerItem?
    var playButton:UIButton?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        let url = URL(string: "https://s3.amazonaws.com/kargopolov/kukushka.mp3")
        let playerItem:AVPlayerItem = AVPlayerItem(url: url!)
        player = AVPlayer(playerItem: playerItem)
        let playerLayer=AVPlayerLayer(player: player!)
        playerLayer.frame=CGRect(x:0, y:0, width:10, height:50)
        self.view.layer.addSublayer(playerLayer)
        
        playButton = UIButton(type: UIButton.ButtonType.system) as UIButton
        let xPostion:CGFloat = 50
        let yPostion:CGFloat = 100
        let buttonWidth:CGFloat = 150
        let buttonHeight:CGFloat = 45
        
        playButton!.frame = CGRect(x: xPostion, y: yPostion, width: buttonWidth, height: buttonHeight)
        playButton!.center = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
        playButton!.backgroundColor = UIColor.lightGray
        playButton!.setTitle("Play", for: UIControl.State.normal)
        playButton!.tintColor = UIColor.black
        playButton!.addTarget(self, action: #selector(self.playButtonTapped(_:)), for: .touchUpInside)
        
        self.view.addSubview(playButton!)
    }
    
    @objc func playButtonTapped(_ sender:UIButton)
    {
        if player?.rate == 0
        {
            player!.play()
            playButton!.setTitle("Pause", for: UIControl.State.normal)
        } else {
            player!.pause()
            playButton!.setTitle("Play", for: UIControl.State.normal)
        }
    }
    
}

Create AVPlayer and AVPlayerItem

Complete Code Example SwiftUI

Here is the complete code example with all the steps combined using SwiftUI:

import SwiftUI
import AVFoundation

struct ContentView: View {
    @State private var player: AVPlayer?
    @State private var playerLayer: AVPlayerLayer?
    @State private var playButtonTitle: String = "Play"
    
    var body: some View {
        VStack {
        
            Button(action: {
                self.playButtonTapped()
            }) {
                Text(playButtonTitle)
                    .foregroundColor(.black)
                    .padding()
                    .background(Color.gray)
                    .cornerRadius(10)
            }
            .padding()
        }
        .onAppear {
            self.setupPlayer()
        }
    }
    
    func setupPlayer() {
        let url = URL(string: "https://s3.amazonaws.com/kargopolov/kukushka.mp3")
        let playerItem:AVPlayerItem = AVPlayerItem(url: url!)
        player = AVPlayer(playerItem: playerItem)
        playerLayer?.frame = CGRect(x:  0, y:  0, width:  10, height:  50)
    }
    
    func playButtonTapped() {
        if player?.rate ==  0 {
            player?.play()
            playButtonTitle = "Pause"
        } else {
            player?.pause()
            playButtonTitle = "Play"
        }
    }
}

Create AVPlayer and AVPlayerItem

Conclusion

I hope this tutorial was helpful to you. Now you can successfully Play Music MP3 files from a Remote URL in Swift.

To learn more about Swift and to find other code examples, check the following page: Swift Code Examples.

Keep coding, and happy learning!

Leave a Reply

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