简体   繁体   中英

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.

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")
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM