LewTrocki
LewTrocki

Reputation: 41

AVPlayer UIButton - show play or pause image button depending on whether the stream is on or off

I have an app, which is playing url mp3 audio with two image buttons - play and stop. Now I would like to improve it a little bit. I have two .png images (play.png and pause.png) right now and I would like them to change with each other with a tap depending on whether the stream is on or off. Any ideas how to make it? Here is my code:

import UIKit
import AVKit
import MediaPlayer

class ViewController: UIViewController, AVAudioPlayerDelegate {
    
    var player : AVPlayer!
    var dict = NSDictionary()
    
    
    
    
    @IBAction func playButtonPressed(_ sender: UIButton){
        let url = "https://stream.com/radio.mp3"
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers, .allowAirPlay])
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, options: [])
            print("Playback OK")
            try AVAudioSession.sharedInstance().setActive(true)
            print("Session is Active")
        } catch {
            print(error)
        }
        
            player = AVPlayer(url: URL(string: url)!)
            player.volume = 1.0
            player.rate = 1.0
            player.play()
        
    
    }
    
    
    
    @IBAction func stopButtonStopped(sender: UIButton) {
        player.pause()
    }

Upvotes: 0

Views: 689

Answers (1)

LewTrocki
LewTrocki

Reputation: 41

My mistake was that I was trying to add pause.png and play.png in sender.setImage(playImage, for: .normal instead of declaring it in let keword:

let play = UIImage(named: "play.png")

The code that actually works is:

@IBAction func buttonPressed(_ sender: UIButton){
          
          if isPlaying {
               player.pause()
               sender.setImage(pauseImage, for: .normal)
          } else {
               let url = "https://stream.com/radio.mp3"
               do {
                    try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers, .allowAirPlay])
                    try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, options: [])
                    print("Playback OK")
                    try AVAudioSession.sharedInstance().setActive(true)
                    print("Session is Active")
               } catch {
                    print(error)
               }
               
               player = AVPlayer(url: URL(string: url)!)
               player.volume = 1.0
               player.rate = 1.0
               player.play()
               sender.setImage(playImage, for: .normal)
          }
          
          isPlaying.toggle()
     }

Upvotes: 1

Related Questions