5

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?

1

2 Answers 2

10

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()
    }
}
2
  • Looks good to me! I used the URL file (#2) for the project, and the audio is playing.
    – darkginger
    Dec 13, 2017 at 7:13
  • 2
    The question is about AVAudioPlayer and not AVPlayer
    – Enrique
    Jun 12, 2020 at 16:52
5

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)
        }
    }
1
  • let soundData = try Data(contentsOf: url) /// it is a line of code that is often unused and causes an error and no sound.
    – PAULMAX
    Apr 12, 2021 at 7:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.