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