我正在建立一個睡眠定時器應用程序,它允許使用9種不同的聲音來幫助你入睡。我需要的最後一件事就是能夠在按下按鈕時播放聲音,並在再次按下時停止播放相同的聲音。我試着這樣做:如何使用單個按鈕啓動和停止音頻?
@IBAction func heavyThunderBtnPressed(_ sender: UIButton) {
heavyThunderBtn.isSelected = true
toggleButton(button: sender, onImage: #imageLiteral(resourceName: "thunderstorm_selected"), offImage: #imageLiteral(resourceName: "thunderstorm_unselected"))
numberOfPresses += 1
if numberOfPresses % 2 == 0 || numberOfPresses == 1 && numberOfPresses != 2 {
do {
rainAudioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "thunder", ofType: "mp3")!))
rainAudioPlayer.prepareToPlay()
rainAudioPlayer.play()
}
catch {
print(error)
}
}
else {
rainAudioPlayer.stop()
}
}
但它可以讓我按下按鈕時,播放音頻和按鈕變爲我選擇顯示的顏色它的上。然後當我再次按下時,音頻重新開始並繼續播放,然後當我再次按下它時,它停止播放,但按鈕再次變爲藍色,表示它已開啓。所以這就是我改變它的原因,但每次按按鈕播放音頻時都會發生崩潰。我得到的錯誤是 「EXC_BAD_ACCESS(代碼= 1,地址= 0×48)」
import UIKit
import AVFoundation
class RainSoundsViewController: UIViewController {
var rainAudioPlayer = AVAudioPlayer()
var numberOfPresses = 0
var tappedAgain: Bool! = false
var heavyThunderOffImage = UIImage()
@IBOutlet weak var backgroundView: UIView!
@IBOutlet weak var heavyThunderBtn: UIButton!
@IBOutlet weak var lightRainBtn: UIButton!
@IBOutlet weak var rainOnRoofBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
heavyThunderOffImage = #imageLiteral(resourceName: "thunderstorm_unselected")
heavyThunderBtn.isSelected = false
backgroundView.layer.cornerRadius = 10
backgroundView.layer.masksToBounds = true
}
@IBAction func dismissPopup(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func heavyThunderBtnPressed(_ sender: UIButton) {
heavyThunderBtn.isSelected = true
toggleButton(button: sender, onImage: #imageLiteral(resourceName: "thunderstorm_selected"), offImage: #imageLiteral(resourceName: "thunderstorm_unselected"))
numberOfPresses += 1
if rainAudioPlayer.isPlaying {
do {
rainAudioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "thunder", ofType: "mp3")!))
rainAudioPlayer.prepareToPlay()
rainAudioPlayer.play()
}
catch {
print(error)
}
}
else {
rainAudioPlayer.stop()
}
}
錯誤是什麼? – Shades
第51行,如果rainAudioPlayer.isPlaying –
[檢查AVAudioPlayer是否正在播放]可能的重複(https://stackoverflow.com/questions/30302640/check-if-avaudioplayer-is-playing) – Shades