Я пробовал вызывать как функции асинхронно, так и оператор печати, чтобы отслеживать функцию, все работает нормально, однако вибрация не работает, когда запись и вибрация выполняются одновременно< /p>
Ниже приведена реализация кода:
import UIKit
import AVFoundation
import Accelerate
import AudioToolbox
класс 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]
}
Подробнее здесь: https://stackoverflow.com/questions/782 ... the-same-t
Мобильная версия