Airplay content to your speaker using Swift

To AirPlay content to speakers using Swift for iOS, you can use the AVAudioSession class. Here’s an example of how you can use this class to play audio on a connected AirPlay speaker:

import AVFoundation
import AVKit

var player: AVPlayer?
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(AVAudioSession.Category.playback)
try audioSession.setActive(true)

let outputRoutes = audioSession.currentRoute.outputs
for route in outputRoutes
  if route.portType == AVAudioSession.Port.airPlay 
    // AirPlay speaker is available
    try audioSession.setPreferredOutput(route)

    // Play your audio using your preferred method (e.g. AVAudioPlayer)

    let urlString = "your url string"
    guard let url = URL.init(string: urlString)
        else {
    let playerItem = AVPlayerItem.init(url: url)
    player = AVPlayer.init(playerItem: playerItem)

Note that this is just a basic example, and you may need to modify the code to meet the specific needs of your app. Additionally, you should also handle error conditions and check for the availability of AirPlay speakers before attempting to play audio on them.

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.