这是我的功能:
func playMusic(filename :String!) {
var playIt : AVAudioPlayer!
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
if url == nil {
println("could not find \(filename)")
return
}
var error : NSError?
playIt = AVAudioPlayer(contentsOfURL: url, error: &error)
if playIt==nil {
println("could not create audio player")
return
}
playIt.numberOfLoops = -1
playIt.prepareToPlay()
playIt.play()
}
我调试了我的应用程序,我看到控制台告诉我:无法创建音频播放器
看起来我的playIt
var是零
我如何解决它?
您的代码还有另一个问题:一旦您发现为什么playIt
是nil
并修复它,您会发现playMusic
运行没有错误,但没有声音播放。那是因为你已经将playIt
声明为playMusic
中的局部变量。正如它开始播放一样,当它的所有局部变量超出范围并且不再存在时,你到达playMusic
的末尾。在playIt
开始播放之后的微秒,它就会消失。
要解决这个问题,请在playIt
之外声明playMusic
作为实例变量。这是一个视图控制器的代码,它使用你的playMusic
方法和我建议的一个改变:
import UIKit
import AVFoundation
class ViewController: UIViewController {
// Declare playIt here instead
var playIt : AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
playMusic("sad trombone.mp3")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonPressed(sender: AnyObject) {
}
func playMusic(filename :String!) {
// var playIt : AVAudioPlayer! *** this is where you originally declared playIt
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
if url == nil {
println("could not find \(filename)")
return
}
var error : NSError?
playIt = AVAudioPlayer(contentsOfURL: url, error: &error)
if playIt==nil {
println("could not create audio player")
return
}
playIt.numberOfLoops = -1
playIt.prepareToPlay()
playIt.play()
}
}
尝试两种方式 - 将playIt
声明为实例变量,将playIt
作为playMusic
中的局部变量。你会想要和前者一起去。
我也是在考虑nhgrif的建议:playMusic应该采用String
或String?
参数;不是String!