如何停止背景声音(swift3)

问题描述 投票:0回答:2

我使用函数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()
}
ios session swift3 avplayer audio-player
2个回答
0
投票

如果你看一下你的代码示例,你就会为play和stop创建一个player的新实例。

您需要为您的播放器创建一个类变量,例如:

var player: AVAudioPlayer?

这将允许你像这样停止:

func slowStop() {
   player?.stop()
}

0
投票

为玩家创建一个像打击一样的实例

 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()
    }

您可以在执行任何操作之前添加验证以检查播放器是否有效。

© www.soinside.com 2019 - 2024. All rights reserved.