2017-07-17 31 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

嘗試檢查'if audioPlayer.isPlaying' – kathayatnk

回答

1

我想你的靜音功能,你可以檢查存在的audioplyer網址,如果它是零隻是返回。例如:

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

我只是想在我調用靜音方法之前沒有初始化實例。而你的方法確實幫助我解決了另一個問題。謝啦 – Nan