I'm new to Swift, but I want to change my view controller to play a remote mp3 file in my iOS app. I started with this code to play a song locally, and it works (with functions for the player after):
import AVFoundation
class Music1ViewController: UIViewController {
//5 -
var songPlayer = AVAudioPlayer()
//15 -
var hasBeenPaused = false
//6 -
func prepareSongAndSession() {
do {
//7 - Insert the song from our Bundle into our AVAudioPlayer
songPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "localsong", ofType: "mp3")!))
//8 - Prepare the song to be played
songPlayer.prepareToPlay()
After looking at the AVAudioPlayer
documentation, .prepareToPlay()
preloads the buffer, which makes me think all I need to do is change the initializer to target a URL.
Then I change the initializer:
songPlayer = try AVAudioPlayer(contentsOf: URL(string: "https://s3.amazonaws.com/kargopolov/kukushka.mp3")!)
I don't get any errors in XCode, but when I run it, I see an error in the console for Thread 1: EXC_BAD_ACCESS (code=1, address=0x48)
which makes me think I am approaching this wrong.
Is there a better way to access the remote mp3 file?
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()
}
}
My approach
func preparePlayer() {
guard let url = URL(string: "https://yourURL.mp3") else {
print("Invalid URL")
return
}
do {
let session = AVAudioSession.sharedInstance()
try session.setCategory(AVAudioSessionCategoryPlayback)
let soundData = try Data(contentsOf: url)
audioPlayer = try AVAudioPlayer(data: soundData)
audioPlayer.volume = 1
let minuteString = String(format: "%02d", (Int(audioPlayer.duration) / 60))
let secondString = String(format: "%02d", (Int(audioPlayer.duration) % 60))
print("TOTAL TIMER: \(minuteString):\(secondString)")
} catch {
print(error)
}
}
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