我正在制作一个音频播放器,仅用于测试我的其他项目。
我将一个名为BackgroundAudio
的类定义如下:
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)
}
}
在我的View Controller中,我通过这样做初始化了类并实现了一些相关的功能:
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
按钮,程序就会崩溃。是因为在按下播放按钮之前按下静音时未初始化类。
如何解决这个问题?提前致谢
答案 0 :(得分:1)
我想在您的静音功能中,您可以检查音频网址是否存在,如果它是零则返回。类似的东西:
if audioPlayer.url != nil { do Stuff } else { do nothing }