我已经在IOS上使用Swift开发了一个应用程序,当你按下一个按钮它会发出声音(我是初学者)。 这段代码虽然一直给我带来问题,但是当我只是把“威廉的尖叫音效”放进去的时候,代码就可以工作了,但是当我尝试输入字符串时它给了我“ViewController.Type没有名为scream的成员”错误
我已经坚持了一段时间,所以任何帮助都会受到赞赏。
class ViewController: UIViewController {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let scream: String = "The Wilhelm scream sound effect"
var pianoSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(scream, ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
}
答案 0 :(得分:0)
您的代码无法在那里工作。你必须把它放在一个函数中,如下所示:
let audioPlayer = AVAudioPlayer()
let scream = "The Wilhelm scream sound effect"
func playMySound(sound:String) {
// you can get the file url instead of the path like this:
let soundUrl = NSBundle.mainBundle().URLForResource(sound, withExtension: "mp3")
// now you can play your audio using the soundUrl
// ...
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
playMySound("The Wilhelm scream sound effect")
// or
playMySound(scream)
}