2017-07-17 9 views
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ボタンを押すとプログラムがクラッシュします。再生ボタンが押される前にミュートを押してもクラスが初期化されないからです。 enter image description here

解決方法事前に感謝します

+0

試しaudioPlayer.isPlaying' – kathayatnk

答えて

1

あなたのミュート機能では、audioplyer URLが存在するかどうかをチェックできます。ような何か:

if audioPlayer.url != nil { do Stuff } else { do nothing } 
+0

場合、私はちょうど私がミュートメソッドを呼び出す前に、インスタンスが初期化されていない把握 'チェック。そしてあなたのアプローチは実際に別の問題を解決するのに役立ちます。ありがとう – Nan

関連する問題