get noise level from apple watch in swift

To get the noise level from an Apple Watch in Swift, you can use the AVAudioRecorder and AVAudioSession classes from the AVFoundation framework.

  1. First, you need to request permission to access the microphone. Add the following code to ViewController.swift:
main.swift
import AVFoundation

AVAudioSession.sharedInstance().requestRecordPermission { (granted) in
    if granted {
        print("Microphone permission granted")
    } else {
        print("Microphone permission denied")
    }
}
223 chars
10 lines
  1. Next, you need to set up the AVAudioRecorder object to start recording sound:
main.swift
var audioRecorder: AVAudioRecorder!

func startRecording() {
    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(.record, mode: .default)
        try audioSession.setActive(true)
        let settings = [
            AVFormatIDKey: Int(kAudioFormatAppleLossless),
            AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue,
            AVEncoderBitRateKey: 320000,
            AVNumberOfChannelsKey: 1,
            AVSampleRateKey: 44100.0
        ]
        audioRecorder = try AVAudioRecorder(url: getDocumentsDirectory().appendingPathComponent("recording.m4a"), settings: settings)
        audioRecorder.delegate = self
        audioRecorder.record()
    } catch {
        print("Error starting recording: \(error.localizedDescription)")
    }
}
803 chars
22 lines
  1. Finally, you can use the averagePower(forChannel: 0) function of the AVAudioRecorder object to get the noise level. Here's an example:
main.swift
let level = audioRecorder.averagePower(forChannel: 0)
print("Noise level: \(level)")
85 chars
3 lines

Remember to stop recording when you're done:

main.swift
func stopRecording() {
    audioRecorder.stop()
}
50 chars
4 lines

Note that you will need to add the AVFoundation framework to your project in order to use these classes.

gistlibby LogSnag