I am getting mp3 url as a response of api calling. I want to play that audio, so how can i do that? (ios swift)
here is my response
{
content =
SWIFT 4
1 - import AVFoundation
2 - declare player
var player : AVPlayer?
3 - in ViewDidLoad call function and pass the streaming url like String
loadRadio(radioURL: (radioStation?.streamURL)!)
4 - function to play
func loadRadio(radioURL: String) {
guard let url = URL.init(string: radioURL) else { return }
let playerItem = AVPlayerItem.init(url: url)
player = AVPlayer.init(playerItem: playerItem)
player?.play()
startNowPlayingAnimation(true)
played = true
}
For me is the best and simply way to streaming audio in swift.
I tried the following,
let urlstring = "http://radio.spainmedia.es/wp-content/uploads/2015/12/tailtoddle_lo4.mp3"
let url = NSURL(string: urlstring)
print("the url = \(url!)")
downloadFileFromURL(url!)
Add the below methods,
func downloadFileFromURL(url:NSURL){
var downloadTask:NSURLSessionDownloadTask
downloadTask = NSURLSession.sharedSession().downloadTaskWithURL(url, completionHandler: { [weak self](URL, response, error) -> Void in
self?.play(URL)
})
downloadTask.resume()
}
And your play method as it is,
func play(url:NSURL) {
print("playing \(url)")
do {
self.player = try AVAudioPlayer(contentsOfURL: url)
player.prepareToPlay()
player.volume = 1.0
player.play()
} catch let error as NSError {
//self.player = nil
print(error.localizedDescription)
} catch {
print("AVAudioPlayer init failed")
}
}
Download the mp3 file and then try to play it, somehow AVAudioPlayer does not download your mp3 file for you. I am able to download the audio file and player plays it.
Remember to add this in your info.plist since you are loading from a http source and you need the below to be set for iOS 9+
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</plist>
var player : AVPlayer?
func playSound()
{
guard let url = URL(string: "https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3")
else
{
print("error to get the mp3 file")
return
}
do{
try AVAudioSession.sharedInstance().setCategory(.playback, mode.default)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVPlayer(url: url as URL)
guard let player = player
else
{
return
}
player.play()
} catch let error {
print(error.localizedDescription)
}
}