Dolan
Dolan

Reputation: 358

Swift - AVAudioPlayer not playing sound

I have a sound called speeding.mp3 and I am trying to make a AVAudioPayer instance with it by doing this in the root of the class:

let speedingAudioPlayer = try! AVAudioPlayer(contentsOfURL: NSBundle.mainBundle().URLForResource("speeding", withExtension: "mp3")!)

Then when I run the app it throws an error but I don't know why this is happening. The speeding.mp3 file is in the Bundle Resources drop down in Build Phases so it should find it fine. If I try to print out the URL in the simulator and paste it into Safari it loads and plays the file like normal. I am importing AVFoundation into the class and the framework into the project.

Upvotes: 0

Views: 2526

Answers (3)

Estevex
Estevex

Reputation: 790

import UIKit
import AVFoundation

class CustomAudioPlayer {
  var audioPlayer : AVAudioPlayer!

  override func viewDidLoad() {
    super.viewDidLoad()
    playSound("sound_file_name")
  }

  func playSound(soundName: String)
  {
    let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "mp3")!)
    do{
        audioPlayer = try AVAudioPlayer(contentsOfURL:alertSound)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }catch {
        print("Error getting the audio file")
    }
  }
}

Try this code for playing the sound.

Upvotes: 1

Dolan
Dolan

Reputation: 358

I found another question where the var is placed outside the class because otherwise it would be deallocated by the phone.

AVAudioPlayer Object Sound Not Playing - Swift

Upvotes: 1

Sandeep
Sandeep

Reputation: 21154

Use this code snippet to debug your error,

if let URL = NSBundle.mainBundle().URLForResource("speeding", withExtension: "mp3") {
    do {
        let speedingAudioPlayer = try AVAudioPlayer(contentsOfURL: URL)
    } catch  let error as NSError {
        print(error.localizedDescription)
    }
} else {
    print("No such file exist")
}

Upvotes: 1

Related Questions