Home > Net >  Swift audio playing from url
Swift audio playing from url

Time:03-18

import AVFoundation
import UIKit

class ViewController: UIViewController {

    @IBOutlet var button: UIButton!

    var player: AVPlayer?
    var playerItem:AVPlayerItem?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func didTapButton(urlRadio: String){
        if let player = player, player.isMuted{
            //stop playback
        }
        else{


            do {
                try AVAudioSession.sharedInstance().setMode(.default)
                try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)

                guard let urlRadio = URL.init(string: "http://live.shtorm.fm:8000/mp3_rushtorm") else {
                    return
                }
            
                let playerItem:AVPlayerItem = AVPlayerItem.init(url: urlRadio)
                player = AVAudioPlayer.init(playerItem: playerItem)
                

            }

            catch {
                print("something went wrong")
            }
        }
    }
}

shows error Exception NSException * "-[RozetkaRadio.ViewController didTapButton]: unrecognized selector sent to instance 0x7ff070f07a50" 0x00006000008c7210 after pressing button in emulator

using storyboard

CodePudding user response:

Your issue is with this line of code. Specifically, the parameter urlRadio.

@IBAction func didTapButton(urlRadio: String){

It looks like you have changed the standard IBAction from what was set in storyboard. You cannot change the parameters in an IBAction as the storyboard no longer recognizes where to send the tap to.

Your IBAction should look something like this

@IBAction func didTapButton(_ sender: Any)

Whenever you see Unrecognized selector sent to instance you should immediately think "Something is not hooked up properly between my storyboard and my ViewController"

One quick way to look is by right clicking your controller scene name on the storyboard. You can see I commented out my SignIn IBAction function. If I wanted to remove it I would have to also remove the connection on the storyboard. You can see the storyboard will let me know by leaving a yellow warning label.

enter image description here

  • Related