ZhouW
ZhouW

Reputation: 1207

Swift: Audio gets laggy and jittery the more times it's played/stopped

I have a simple app that allows the user to record sound and then play it back. However, I've found that the more times recordings are saved and deleted, the laggier the audio playback becomes. This is an example of what happens to the sound quality:

Laggy audio

Normal audio

If in xcode I exit the app in the simulator and re-open it, the audio quality is back to normal, but for whatever reason going to a different UIViewController in the app and then going back to the main screen (so it's reloaded completely, and the viewDidLoad() gets run again etc) will not make the audio quality go back to normal.

I don't know what's causing the audio to become laggier and laggier as more recordings are made and deleted, and am wondering if there's some code to reset audio settings completely.

This is basically how I'm recording audio:

        var recordSettings = [
        // AVFormatIDKey: kAudioFormatAppleLossless,
        AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue,
        AVEncoderBitRateKey : 320000,
        AVNumberOfChannelsKey: 2,
        AVSampleRateKey : 44100.0
    ]


    var session=AVAudioSession.sharedInstance()
    session.setCategory(AVAudioSessionCategoryPlayAndRecord,error:nil)
    audioRecorder = AVAudioRecorder(URL: filePathForRecordedAudio, settings: recordSettings, error:nil)
    audioRecorder.delegate = self
    audioRecorder.meteringEnabled=true
    audioRecorder.prepareToRecord()
    audioRecorder.record()

Then when the recording is stopped by the user I run this:

session.setCategory(AVAudioSessionCategoryPlayback,error:nil)

And recorded audio is played back the normal way:

var player:AVAudioPlayer = AVAudioPlayer()
player = AVAudioPlayer(contentsOfURL: NSURL(string: "\(locationOfRecordedAudio)"), error: nil)
player.play()

Upvotes: 2

Views: 211

Answers (2)

August Lin
August Lin

Reputation: 1279

        DispatchQueue.global(qos: .background).async {
            recorder.stop();
        }

Upvotes: 0

SwiftArchitect
SwiftArchitect

Reputation: 48532

You are probably adding runtime threads.

audioRecorder.stop()

Upvotes: 1

Related Questions