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