CadeLewis
CadeLewis

Reputation: 83

iOS AVAudioPlayer - how to set file path to the pathForResource

i want to play small mp3 file when button is clicked. but not sure how to set the mp3 file in setPathForResources

Here My Code

import UIKit
import AVFoundation
class PlaySoundsViewController: UIViewController {

    var coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("/sounds/superman", ofType: "mp3")!)
    var audioPlayer = AVAudioPlayer()


    @IBOutlet weak var PlaySlow: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

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

    @IBAction func PlaySlowAction(sender: UIButton) {
      audioPlayer.play()
    }

I have added the sounds folder to the project using just drag and drop. but when i click button im getting this error.

audioPlayer.play() Thread 1: EXC_BAD_ACCESS(Code=1,address=0x1c)

Upvotes: 2

Views: 1479

Answers (2)

user470763
user470763

Reputation:

You don't need the sounds/ in your path. Just the filename. e.g.

var coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("superman", ofType: "mp3")!)

Also fileURLWithPath takes a URL, not a string. You need to convert your NSBundle.mainBundle().pathForResource("superman", ofType: "mp3") to a string first using NSURL(string:).

This is the full setup:

let path = NSBundle.mainBundle().pathForResource("superman", ofType:"mp3")
let fileURL = NSURL(fileURLWithPath: path)
player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
player.prepareToPlay()
player.delegate = self
player.play()

Upvotes: 2

Michael Dautermann
Michael Dautermann

Reputation: 89509

You missed a couple necessary steps in your "PlaySlowAction" method:

@IBAction func PlaySlowAction(sender: UIButton) {

    // if the audioPlayer hasn't been set to any sound file yet, 
    // load it up...
    if(audioPlayer.data == nil)
    {
        var error:NSError?
        audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: &error)
        if let actualError = error {
            println("An Error Occurred: \(actualError)")
        }
    }
    audioPlayer.prepareToPlay()
    audioPlayer.play()

}

Upvotes: 1

Related Questions