他のプロジェクトのテスト用にオーディオプレーヤーを作成しています。 私は、次のよう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
ボタンを押すとプログラムがクラッシュします。再生ボタンが押される前にミュートを押してもクラスが初期化されないからです。
解決方法事前に感謝します
試しaudioPlayer.isPlaying' – kathayatnk