0
我正在製作音頻播放器,僅用於測試其他項目。 我定義了一個名爲BackgroundAudio
類如下:AVAudioPlayer問題導致應用程序崩潰
class BackgroundAudio: NSObject,AVAudioPlayerDelegate {
var audioPlayer = AVAudioPlayer()
override init() {
super.init()
}
func play(audioOfUrl:URL) {
let urlPath = audioOfUrl
do {
audioPlayer = try AVAudioPlayer.init(contentsOf: urlPath)
audioPlayer.delegate = self
audioPlayer.play()
} catch let error {
print(error.localizedDescription)
}
}
func stop() {
audioPlayer.stop()
}
func mute() {
audioPlayer.setVolume(0, fadeDuration: 2)
}
func unMute() {
audioPlayer.setVolume(1, fadeDuration: 2)
}
}
在我的視圖控制器,我初始化類,並通過這樣實現的一些相關功能:
class ViewController: UIViewController {
var urlPath = Bundle.main.url(forResource: "Focus", withExtension: "mp3")!
var backgroundAudio:BackgroundAudio?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
backgroundAudio = BackgroundAudio()
}
@IBAction func playButtonTapped(_ sender: Any) {
backgroundAudio?.play(audioOfUrl: urlPath)
}
@IBAction func stopButtonTapped(_ sender: Any) {
backgroundAudio?.stop()
}
@IBAction func muteButtonTapped(_ sender: Any) {
backgroundAudio?.mute()
}
@IBAction func unMuteButtonTapped(_ sender: Any) {
}
}
一切都工作得很好,但提出的問題。問題是這樣的:
如果我點擊play
按鈕,它的工作原理,但如果我按mute
按鈕,程序崩潰。是因爲在按下播放按鈕之前按下靜音時,該類未被初始化。
如何解決這個問題?在此先感謝
嘗試檢查'if audioPlayer.isPlaying' – kathayatnk