I am trying to make a vibration test which produces vibration for 3 sec and tries to record the vibration, the goal is to analyze frequency of vibration so that we can check if vibration is working on my iphone and if the vibration or haptic motor isn't faulty.
I have tried calling both the functions asynchronously and the print statement to trace the function work completely fine, however the vibration doesnt perform when recording and vibration are performed simultaneously
Below is the code implementation:
import UIKit
import AVFoundation
import Accelerate
import AudioToolbox
class ViewController: UIViewController, AVAudioRecorderDelegate {
var vibrationTimer: Timer?
var endTime: Date?
var audioRecorder: AVAudioRecorder?
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func testButtonPressed(_ sender: UIButton) {
playVibrationForDuration(seconds: 3)
}
//play vibration
func playVibrationForDuration(seconds: TimeInterval) {
// Set the end time for vibration
endTime = Date().addingTimeInterval(seconds)
// Start playing vibration and record it simultaneously using Dispatch queue for asyncjronous calls
DispatchQueue.global(qos: .background).async {
// Start vibration
self.startVibration()
}
DispatchQueue.global(qos: .background).async {
// Start recording
self.startRecording()
}
}
func startVibration() {
print("Vibration starts")
// Schedule timer to play vibration repeatedly
vibrationTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(playVibration), userInfo: nil, repeats: true)
}
@objc func playVibration() {
guard let endTime = endTime, Date() < endTime else {
// Stop the vibration when the end time is reached
stopVibration()
return
}
// Play system sound for vibration
AudioServicesPlaySystemSound(1352)
}
func stopVibration() {
// Invalidate timer to stop vibration
vibrationTimer?.invalidate()
print("Vibration stops")
}
//record the vibrations produced
func startRecording() {
print("Recording started")
let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.m4a")
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 44100,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
do {
audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
audioRecorder?.delegate = self
audioRecorder?.record()
} catch {
print("Error recording audio: \(error.localizedDescription)")
}
// analyzeRecordedVibration(audioURL: audioFilename)
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
I haven't incuded the code for analysis part.