First of all let me say that I am very new to programming. What I'm trying to do is add a button that when pressed plays music, and when pressed again the music stops. Ideally when the button is pressed for a third time the music will have reset. Whilst trying to achieve this I'm getting the error message "Expression resolves to an unused function", as I am very new all the help I find online doesn't make any sense to me.
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}
}
}
Swooping in here after Martin R's comment ...
if audioPlayer.playing { audioPlayer.stop} else { audioPlayer.play}
On this line, you are not calling the stop
and play
functions, but simply accessing them. Resolving to an unused function
is trying to tell you that you have an expression that is returning a function type, but you are never calling it (audioPlayer.stop
and audioPlayer.play
are the expressions in question here).
To rid yourself of this error, and probably produce the correct behavior, try calling the functions.
if audioPlayer.playing {
audioPlayer.stop()
} else {
audioPlayer.play()
}
Swift 4: Just add the braces '()' next to the method name
override func viewWillAppear(_ animated: Bool) {
addView //error: Expression resolves to an unused function
}
func addView(){
}
Solution:
override func viewWillAppear(_ animated: Bool) {
addView()
}
Here's a simplified version of Brian's answer:
audioPlayer.playing
? audioPlayer.stop()
: audioPlayer.play()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With