In this Swift code example, you will learn how to play the music mp3 file from a remote URL in Swift.
The code example below will cover:
- Create AVPlayer and AVPlayerItem,
- Create UIButton programmatically,
- Create AVPlayerLayer and add it as a subview,
- Handle the Play button action to Pause and Play music,
- Set UIImage on the Play button if needed.
Using AVPlayer to play MP3 File
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!.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!.setImage(UIImage(named: "player_control_pause_50px.png"), forState: UIControlState.Normal) playButton!.setTitle("Pause", for: UIControl.State.normal) } else { player!.pause() //playButton!.setImage(UIImage(named: "player_control_play_50px.png"), forState: UIControlState.Normal) playButton!.setTitle("Play", for: UIControl.State.normal) } } }
For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.