在线通常AVAudioPlayer
教程在函数中创建AVAudioPlayer
,其中AVAudioPlayer
对象的播放和停止功能不能直接从其他函数对对象使用。问题是我想要另一个函数来阻止来自AVAudioPlayer
的声音。通过初始化类顶部的对象希望它可以访问,这似乎非常简单,但是Swift3
init
AVAudioPlayer
throw
函数包含import UIKit
import AVFoundation
class MadLibOneViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var thePlace: UITextField!
@IBOutlet weak var theVerb: UITextField!
@IBOutlet weak var theNumber: UITextField!
@IBOutlet weak var theTemplate: UITextView!
@IBOutlet weak var theStory: UITextView!
@IBOutlet weak var generateStoryButton: UIButton!
@IBOutlet weak var proceedToNextMadLib: UIButton!
//var backgroundMusicPlayer = AVAudioPlayer()
var error:NSError?
var path = Bundle.main.path(forResource: "bensound-cute", ofType: "mp3")
var url: NSURL {
return NSURL(fileURLWithPath: path!)
}
var backgroundMusicPlayer: AVAudioPlayer = try AVAudioPlayer(contentsOf: url as URL, error: &error)
@IBAction func createStory(_ sender: AnyObject) {
theStory.text=theTemplate.text
theStory.text=theStory.text.replacingOccurrences(of: "<place>", with: thePlace.text!)
theStory.text=theStory.text.replacingOccurrences(of: "<verb>", with: theVerb.text!)
theStory.text=theStory.text.replacingOccurrences(of: "<number>", with: theNumber.text!)
generateStoryButton.isHidden=true
proceedToNextMadLib.isHidden=false
}
@IBAction func showNextStory(_ sender: AnyObject) {
view.backgroundColor=UIColor.green
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let resultViewController = storyBoard.instantiateViewController(withIdentifier: "MadLibTwoViewController") as! MadLibTwoViewController
self.present(resultViewController, animated:true, completion:nil)
}
@IBAction func hideKeyboard(_ sender: AnyObject) {
thePlace.resignFirstResponder()
theVerb.resignFirstResponder()
theNumber.resignFirstResponder()
theTemplate.resignFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
proceedToNextMadLib.isHidden=true
view.backgroundColor = UIColor.purple
// Do any additional setup after loading the view.
self.theVerb.delegate = self
self.thePlace.delegate = self
self.theNumber.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
和参数对于声音文件。 Swift不允许我们在属性初始化程序中使用实例成员,所以我一直坚持我的思考过程如何编写。
此时遇到的唯一错误是在创建&#34; backgroundMusicPlayer&#34;
时,不允许在属性初始值设定项中使用实例成员querySelector
答案 0 :(得分:1)
您需要使用Lazy initialisation/instantiation
。在你的情况下,这就是你需要做的一切。
lazy var player: AVAudioPlayer = {
[unowned self] in
do {
return try AVAudioPlayer.init(contentsOf: self.url)
}
catch {
return AVAudioPlayer.init()
}
}()
有关Lazy Initialisation
this的更多信息,请阅读。在您的情况下,有趣的是初始化throws
。我认为this forum discussion有助于略微了解。