Reputation: 8995
Copied and Pasted this code principally. Compiles and runs, but plays nothing. Using Xcode 7.1 and IOS 9.1. What have I missed... Loaded sound file into main program and AVAssets...
import UIKit
import AVFoundation
class ViewController: UIViewController {
var buttonBeep : AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
buttonBeep = setupAudioPlayerWithFile("hotel_transylvania2", type:"mp3")
//buttonBeep?.volume = 0.9
buttonBeep?.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer? {
//1
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
let url = NSURL.fileURLWithPath(path!)
//2
var audioPlayer:AVAudioPlayer?
// 3
do {
try audioPlayer? = AVAudioPlayer(contentsOfURL: url)
} catch {
print("Player not available")
}
return audioPlayer
}
}
Upvotes: 3
Views: 166
Reputation: 70094
You've got this line backwards:
try audioPlayer? = AVAudioPlayer(contentsOfURL: url)
It should be:
audioPlayer = try AVAudioPlayer(contentsOfURL: url)
Side note: the conversion to and from NSString is not necessary here, just use String - and you should not force unwrap the result of NSBundle:
func setupAudioPlayerWithFile(file:String, type:String) -> AVAudioPlayer? {
//1
guard let path = NSBundle.mainBundle().pathForResource(file, ofType: type) else {
return nil
}
let url = NSURL.fileURLWithPath(path)
//2
var audioPlayer:AVAudioPlayer?
// 3
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: url)
} catch {
print("Player not available")
}
return audioPlayer
}
Upvotes: 1