2015-12-23 34 views
1

我使用AVAudioPlayer,在我viewDidLoad中方法中,首先它的运行良好,但是当我再次来到同一个视图控制器的那首歌开始运行与最初的歌曲打成一片。如何检查AVAudioPlayer仍在运行?

,所以我试图找出是宋在后台运行?

这是我的职责,我调用这个函数在视图中做负载

func prepareAudio() 
    { 
     if audioPlayer.playing 
     { 
      audioPlayer.stop() 
     } 
     do 
     { 

       audioPlayer=try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Kids", ofType: ".mp3")!), fileTypeHint: AVFileTypeMPEGLayer3) 
       audioPlayer.delegate=self; 
       self.audioPlayer.play() 

     } 
     catch 
     { 
      print(error) 
     } 

    } 

但是当我试图运行及彼崩溃 if audioPlayer.playing

帮我找到解决方案这..

第二次尝试

enter image description here

第三尝试

enter image description here

第四尝试

enter image description here

+0

您可以在此行设置断点。我猜你audioPlayer =零 –

+0

是我audioplayer =零@CongTran –

+0

所以你必须检查它是否=零&& .playing =真! - >调用stop()方法 –

回答

0

你必须检查变量是否仍然有效(if not nil

试试这个

if ((!audioPlayer) && (audioPlayer.playing == YES)) 
{ 
    audioPlayer.stop() 
} 
+0

是的,你也可以检查是否(!audioPlayer && audioPlayer.playing) –

1
if let audioPlayer = audioPlayer where audioPlayer.playing { 
    audioPlayer.stop() 
} 

// create your audio player and set the delegate etc. 

不过,我会鼓励你,如果audioPlayer不是零,你不应该总是初始化再次在audioPlayer。

if let audioPlayer = audioPlayer { 
    if audioPlayer.playing { 
     audioPlayer.stop() 
    } 
} else { 
    // setup the audioPlayer and set the delegate 
} 

audioPlayer?.play() 
相关问题