简体   繁体   中英

How to stop background sound (swift3)

I used the function slowPlay to create an action that will play background music. I tried to do the reverse in stop to stop the music. But the music does not stop.

I just want to have a button that plays the music and stops the music. I'm using the code:

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

If you look at your code example you are creating a new instance of the player for both play and stop.

You need to create a class variable for your player, something like:

var player: AVAudioPlayer?

This will allow you to stop like this:

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

Create a single instance for player like blow

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

You can add validation to check whether player is valid or not before performing any action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM