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")
}
}
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()
}
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")
}
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)
}
}
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With