Search code examples
xcodeswift3nsbundle

Error with NSBundle.mainBundle when adding sound


I've trying to create a simple sound board for when a button is pressed a sound is made, however when I used this code

let url = NSURL(fileURLWithPath: Bundle.mainBundle().pathForResource(sound, ofType: "mp3")!)
let audioPlayer = try AVAudioPlayer(contentsOfURL: url)

I get an error with "Bundle.mainBundle" orginally it told me to change "Bundle" from "NSBundle" because it has be renamed but when I correct that I get another error saying "Cannot call value for non-function type 'Bundle' "

my entire code:

import UIKit
import AVFoundation

class ViewController: UIViewController {


let soundFilenames = ["60gs", "check", "dada", "danceforme", "eat", "gods", "irelandbaby", "ko'd", "lefthand", "littlewerp", "nocalls", "precision", "sundaymorning", "surprise", "whothefuckisthatguy", "youlldonothing"]

var audioPlayers = [AVAudioPlayer]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    for sound in soundFilenames {

        do {

            let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!
            let audioPlayer = try AVAudioPlayer(contentsOfURL: url)

            audioPlayer.append(audioPlayer())
        }
        catch {

            audioPlayers.append(AVAudioPlayer())

        }
    }



}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func buttonTapped(_ sender: UIButton) {

    let audioPlayer = audioPlayers[sender.tag]
    audioPlayer.play()

}

}

can anyone help me with this please.


Solution

  • First of all in Swift 3 mainBundle() became main but why not the real short way:

    let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!
    

    And the init method has been renamed to

    let audioPlayer = try AVAudioPlayer(contentsOf: url)
    

    and change the next line to:

    audioPlayers.append(audioPlayer)