Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 511
Ari Jain Avatar asked Jan 18 '26 13:01

Ari Jain


1 Answers

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

like image 95
Kakashi Avatar answered Jan 21 '26 07:01

Kakashi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!