Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AVAudioPlayer to play remote mp3 file in Swift

Tags:

ios

swift

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?

like image 670
darkginger Avatar asked Dec 11 '22 08:12

darkginger


2 Answers

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()
    }
}
like image 148
Ashish Bahl Avatar answered Jan 01 '23 11:01

Ashish Bahl


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)
        }
    }
like image 41
Michel Anderson Lütz Teixeira Avatar answered Jan 01 '23 09:01

Michel Anderson Lütz Teixeira