2017-05-12 24 views
-3

如何使用单个按钮来播放和停止音乐,就像在iTunes中一样。当按下按钮时,再次按下同一按钮应停止播放音乐。使用相同的按钮快速播放和停止音乐

var audioplayer = AVaudioPlayer 
@IBAction func play(_ sender: Any) { 

    do 
    { 

     audioPlayer = try AVAudioPlayer (contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "bensound", ofType: "mp3")!)) 
     audioPlayer.prepareToPlay() 
     audioPlayer.play() 
     audioPlayer.stop() 

    } 
    catch { 
     print ("error") 

    } 

} 

回答

2

显然,这是行不通的:

audioPlayer.prepareToPlay() 
audioPlayer.play() // this will just start playing the music and immediately stop it. 
audioPlayer.stop() 

你需要一个if语句和指示音乐是否正在播放一个变量。

幸运的是,我所说的变量已经存在了!你甚至不需要自己申报!它是isPlaying,在AVAudioPlayer中定义。

我们只需要编写if语句。这是很简单的,

如果正在播放的音乐,阻止它,否则,启动它

if audioplayer.isPlaying { 
    audioplayer.play() 
} else { 
    audioplayer.stop() 
}