我使用函数slowPlay
创建一个将播放背景音乐的动作。我试图在stop
反向停止音乐。但音乐并没有停止。
我只想要一个播放音乐的按钮并停止播放音乐。我正在使用代码:
@IBAction func play(_ sender: Any) {
slowPlay
}
@IBAction func stop(_ sender: Any) {
slowStop
}
func slowPlay() {
do {
let ap = Bundle.main.path(forResource: "slowslow", ofType: "mp3")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: ap!) as URL)
} catch {
////
}
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayback)
} catch {
}
player?.play()
}
func slowStop() {
do {
let ap = Bundle.main.path(forResource: "slowslow", ofType: "mp3")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: ap!) as URL)
} catch {
////
}
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayback)
} catch {
}
player?.stop()
}
如果你看一下你的代码示例,你就会为play和stop创建一个player
的新实例。
您需要为您的播放器创建一个类变量,例如:
var player: AVAudioPlayer?
这将允许你像这样停止:
func slowStop() {
player?.stop()
}
为玩家创建一个像打击一样的实例
var player: AVAudioPlayer?
func slowPlay() {
do {
let ap = Bundle.main.path(forResource: "slowslow", ofType: "mp3")
self.player = try AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: ap!) as URL)
} catch {
////
}
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayback)
} catch {
//catch error here
}
self.player?.play()
}
func slowStop() {
self.player?.stop()
}
您可以在执行任何操作之前添加验证以检查播放器是否有效。