首先让我说我对编程很新.我要做的是添加一个按钮,当按下该按钮播放音乐时,再次按下时按钮音乐停止.理想情况下,当第三次按下按钮时,音乐将重置.在尝试实现这一目标的同时,我收到错误消息"表达式解析为未使用的函数",因为我很新,我在网上找到的所有帮助对我都没有任何意义.
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var janitor: UIImageView!
var pianoSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("C", ofType: "m4a")!)
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
audioPlayer = AVAudioPlayer(contentsOfURL: pianoSound, error: nil)
audioPlayer.prepareToPlay()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func PianoC(sender: AnyObject) {
audioPlayer.play()
if audioPlayer.playing { audioPlayer.stop} else { audioPlayer.play}
}
}
Run Code Online (Sandbox Code Playgroud)
Bri*_*acy 25
在Martin R的评论之后在这里俯冲......
if audioPlayer.playing { audioPlayer.stop} else { audioPlayer.play}
Run Code Online (Sandbox Code Playgroud)
在这一行中,您不是在调用stop和play函数,而只是访问它们.Resolving to an unused function是想告诉你,你有一个函数返回一个函数型的表达式,但你永远不会调用它(audioPlayer.stop和audioPlayer.play这里是有问题的表述).
要摆脱这个错误,并可能产生正确的行为,请尝试调用函数.
if audioPlayer.playing {
audioPlayer.stop()
} else {
audioPlayer.play()
}
Run Code Online (Sandbox Code Playgroud)
Nai*_*hta 10
Swift 4:只需在方法名称旁边添加大括号“()”
override func viewWillAppear(_ animated: Bool) {
addView //error: Expression resolves to an unused function
}
func addView(){
}
Run Code Online (Sandbox Code Playgroud)
解决方案:
override func viewWillAppear(_ animated: Bool) {
addView()
}
Run Code Online (Sandbox Code Playgroud)
这是Brian的答案的简化版本:
audioPlayer.playing
? audioPlayer.stop()
: audioPlayer.play()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20928 次 |
| 最近记录: |