17

I am not an IOS programmer but I need a simple app to play an audio stream from a wowza server. Here is my code, I get no errors but also no audio. Any guidances or help?

    import UIKit
    import AVFoundation

    class ViewController: UIViewController {

         var player = AVAudioPlayer()

        override func viewDidLoad() {
            super.viewDidLoad()

            var fileURL: NSURL = NSURL(string: "http://url----.com/playlist.m3u8")

            var error:NSError?
            player = AVAudioPlayer(contentsOfURL: fileURL, error: &error)

            if player.prepareToPlay() && player.play(){
                println("yes")
            } else {
                println("no")
            }
        }
David Turton
  • 385
  • 2
  • 5
  • 15

7 Answers7

28

This worked for me:

var player = AVPlayer()

func configureView() {

    let url = "http://stream.your.url.com"
    let playerItem = AVPlayerItem( URL:NSURL( string:url ) )
    player = AVPlayer(playerItem:playerItem)
    player.rate = 1.0;
    player.play()

}
2075
  • 405
  • 4
  • 8
  • 6
    it also works if you create 'AVPlayer' directly with url like this: 'avPlayer = AVPlayer(URL: nsUrl)' Only thing you should do is create avPlayer as instance variable if you create avPlayer as local variable it is not working for me. – Aks Apr 14 '15 at 07:16
  • Nice! After I've created AVPlayer as instance variable it started to play! – Alex Nov 27 '16 at 13:30
  • if my url is correct and internet is available, does `avPlayer.play()` guarantees that my audio will play?. is there any try catch to know if play() was successfull or not ? – Awais Fayyaz Oct 23 '18 at 14:00
  • Also, it does play with a little delay. How can i show some loading indicator in that time? – Awais Fayyaz Oct 23 '18 at 14:03
  • This does not work in iOS 14.5 / Swift 5.2+ – FontFamily May 11 '21 at 22:07
11

In Swift 2.0 and iOS 9

do {
    let url = "http://yourdomain.com/file.mp3"
    let fileURL = NSURL(string:url)
    let soundData = NSData(contentsOfURL:fileURL!)
    self.audioPlayer = try AVAudioPlayer(data: soundData!)
    audioPlayer.prepareToPlay()
    audioPlayer.volume = 1.0
    audioPlayer.delegate = self
    audioPlayer.play()
} catch {
    print("Error getting the audio file")
}
thyago stall
  • 1,654
  • 3
  • 16
  • 30
Jsonras
  • 1,120
  • 13
  • 10
7

This anwser helped me: AVAudioPlayer with external URL to *.m4p

I had to convert thr URL to NSData:

func musicFromURL(streamURL: String) {
    guard let fileURL = URL(string:streamURL) else { return  }
    do {
        let soundData = try Data(contentsOf: fileURL)
        self.audioPlayer = try AVAudioPlayer(data: soundData)
        guard let audioPlayer = audioPlayer else { return }
        audioPlayer.prepareToPlay()
        audioPlayer.volume = 1.0
        audioPlayer.play()
    } catch {
        print(error)
    }
}
FontFamily
  • 355
  • 4
  • 13
Billy Coover
  • 3,827
  • 5
  • 36
  • 50
  • 4
    Keep in mind this option involves downloading the mp3 and then playing it. With AVPlayer you can actually stream it. – Dylan Reich Jun 17 '15 at 17:34
  • 1
    This is the only answer that has worked for me for Swift 5 / iOS 14. The code above does have issues and I have made some revisions to make it compatible with iOS 14. The main issue with the edits is that it is still not an asynchronous solution, so there will be a delay before the audio plays. – FontFamily May 11 '21 at 22:05
  • @FontFamily this solution fully downloads the file before playing. Keep it in mind. AvPlayer can stream the file downloading only part of the file to play. This will speed up the playback dramatically depending on the audio file size. – atereshkov Nov 30 '21 at 06:06
2

Please keep in mind since iOS 9: App Transport Security (ATS) configured?

<key>NSAppTransportSecurity</key>
<dict>
   <key>NSExceptionDomains</key>
   <dict>
      <key>yourserver.com</key>
      <dict>
         <!--Include to allow subdomains-->
         <key>NSIncludesSubdomains</key>
         <true/>
         <!--Include to allow HTTP requests-->
         <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
         <true/>
         <!--Include to specify minimum TLS version-->
         <key>NSTemporaryExceptionMinimumTLSVersion</key>
         <string>TLSv1.1</string>
      </dict>
   </dict>
</dict>

Swift 2:

let url = "http://yourserver.com/source.mp3"
    let playerItem = AVPlayerItem(URL:NSURL(string:url)!)
    audio = AVPlayer(playerItem:playerItem)
    audio.rate = 1.0;
    audio.play()
0

To check for error in Swift, use:

if let errorDetails = error {
    println("Error creating player: \(errorDetails.localizedDescription)")
} else {
    if player.prepareToPlay() && player.play(){
        println("yes")
    } else {
        println("no")
    }
}
Raptor
  • 53,206
  • 45
  • 230
  • 366
  • Error creating player: The operation couldn’t be completed. (OSStatus error 2003334207.). – David Turton Sep 18 '14 at 02:14
  • 2
    the error `2003334207` means `AVAudioPlayer` requires a local file. Download it from Internet & save it to local before playing it. Hint: use `writeToFile` – Raptor Sep 18 '14 at 02:21
0

use AVPlayer:

var player:AVPlayer!
var steamingURL:NSURL = NSURL(string:playerURL)
player = AVPlayer(URL: steamingURL)
player.play()
Ramesh
  • 617
  • 6
  • 16
0

//Create AVPlayer Instance in globally

var avPlayer:AVPlayer!


override func viewDidLoad() {
    super.viewDidLoad()
    let urlString = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
    let url = NSURL(string: urlString)!
    avPlayer = AVPlayer(url: url as URL)

    print("About to play...")
    avPlayer.play()
   print("isplaying")
}
khusboo suhasini
  • 293
  • 2
  • 16