How to Play Mp3 Audio from Url in iOS Swift

How to play mp3 audio from URL in iOS 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>

Using AVAudioPlayer to play remote mp3 file in Swift

Try this code :

You need to add AVKit & AVFoundation to your frameworks path and import them :

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {

var player = AVPlayer()

override func viewDidLoad() {
super.viewDidLoad()
}

@IBAction func localPress(_ sender: Any) {
let path = Bundle.main.resourcePath!+"/sound.mp3"
print(path)
let url = URL(fileURLWithPath: path)

let playerItem = AVPlayerItem(url: url)
player = AVPlayer(playerItem: playerItem)
player.play()
}// i have created a btn for playing a local file, this is it's action


@IBAction func urlPressed(_ sender: Any) {

let playerItem = AVPlayerItem(url: URL(string: "https://yourURL.mp3")!)
player = AVPlayer(playerItem: playerItem)
player.play()
}// i have created another btn for playing a URL file, this is it's action

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

playing a url link instead of a .mp3 file in swiftui

You can use AVPlayer to stream resources from a URL like this. I'd also move the streaming/async logic into an ObservableObject:


class SoundManager : ObservableObject {
var audioPlayer: AVPlayer?

func playSound(sound: String){
if let url = URL(string: sound) {
self.audioPlayer = AVPlayer(url: url)
}
}
}

struct ContentView: View {
@State var song1 = false
@StateObject private var soundManager = SoundManager()

var body: some View {
Image(systemName: song1 ? "pause.circle.fill": "play.circle.fill")
.font(.system(size: 25))
.padding(.trailing)
.onTapGesture {
soundManager.playSound(sound: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3")
song1.toggle()

if song1{
soundManager.audioPlayer?.play()
} else {
soundManager.audioPlayer?.pause()
}
}
}
}

How to play a sound on iOS 11 with swift 4? And where i place The mp3 file?

SWIFT 4 / XCODE 9.1

import AVFoundation

var objPlayer: AVAudioPlayer?

func playAudioFile() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }

do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)

// For iOS 11
objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

// For iOS versions < 11
objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3)

guard let aPlayer = objPlayer else { return }
aPlayer.play()

} catch let error {
print(error.localizedDescription)
}
}


Related Topics



Leave a reply



Submit