Ari Jain
Ari Jain

Reputation: 111

Is there a way to play music with AVAudioPlayer on Swift at a specified time?

I am trying to record the AudioPlayer's current time using AVAudioPlayer.currentTime and then pause it. Then use AVAudioPlayer.play(atTime: *double*) to play the song at the specified time.

My code:

var greenCurrentTime = 0.0
var greenButton = false
var trackRight = AVAudioPlayer()

//the if statement is supposed to record the time when the button is pressed for the first time, and the else is supposed to play the audio from the time specified in the if statement when the button is pressed for the second time, i want the audio to be able to go back and play from a previous time 
//the track is already playing

@IBAction func greenHotCue(_ sender: Any) {
        if (greenButton == false) {
            greenCurrentTime = trackRight.currentTime
            print(greenCurrentTime)
            print(greenButton)
            greenButton = true
        }
        else {
            trackRight.prepareToPlay()
            trackRight.play(atTime: greenCurrentTime)
            trackRight.play()
            print(greenCurrentTime)
            print(greenButton)
        }
    }

The above code executes, but nothing happens during its execution and a track continues to play as if the code in the else statement doesn't run at all.

Could you please advise?

Upvotes: 3

Views: 4057

Answers (1)

Kakashi
Kakashi

Reputation: 563

Swift 5

You can set property AVAudioPlayer's currenTime for specific time to play audio.

audioPlayer.currentTime = 5.0  // Start play audio at 5 seconds.

Example:

class TestVC : UIViewController {
    private var audioPlayer: AVAudioPlayer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "/Sounds/sound.aac", ofType: nil)!)
        try! AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category(rawValue: convertFromAVAudioSessionCategory(AVAudioSession.Category.playback)))
        try! AVAudioSession.sharedInstance().setActive(true)
    
        try! audioPlayer = AVAudioPlayer(contentsOf: alertSound)
        audioPlayer!.prepareToPlay()
    
        let shortStartDelay: TimeInterval = 0.01    // seconds
        let now: TimeInterval = audioPlayer?.deviceCurrentTime ?? 0
    
        let timeDelayPlay: TimeInterval = now + shortStartDelay
        audioPlayer?.currentTime = 5.0 // Specific time to start play
        audioPlayer?.play(atTime: timeDelayPlay)
    }

}

Update

If you found: "Cannot find 'convertFromAVAudioSessionCategory' in scope" You can fix with this below.

fileprivate func convertFromAVAudioSessionCategory(_ input: AVAudioSession.Category) -> String {
    return input.rawValue
}

Thank you, nightguard

Ref: https://github.com/nightscout/nightguard/blob/master/nightguard/VolumeChangeDetector.swift

Upvotes: 5

Related Questions