준진의 블로깅
Home
  • 분류 전체보기 (141)
    • NO TITLE (2)
    • 개발 (69)
    • 이모티콘 (5)
    • 개인사업자 & 세금 (14)
    • 부동산 & 인테리어 (8)
    • 여행 (7)
      • 제주도 (0)
      • 미국서부(2019) (4)
      • 스페인(2017) (1)
    • 맛집 (5)
      • 분당, 서현, 판교 (5)
    • 반려견 (10)
    • 프랑스어 (18)
Home
  • 분류 전체보기 (141)
    • NO TITLE (2)
    • 개발 (69)
    • 이모티콘 (5)
    • 개인사업자 & 세금 (14)
    • 부동산 & 인테리어 (8)
    • 여행 (7)
      • 제주도 (0)
      • 미국서부(2019) (4)
      • 스페인(2017) (1)
    • 맛집 (5)
      • 분당, 서현, 판교 (5)
    • 반려견 (10)
    • 프랑스어 (18)
블로그 내 검색

준진의 블로깅

맛집, 개인사업자 정보, 개발, 여행 등등 잡다구리

  • 개발

    [iOS] Audio Sound Level 측정하기

    2020. 12. 2.

    by. dundin

    반응형

    목표 

    현재 device 에서 녹음되고 있는 소리의 sound level를 시각적으로 표현하려고 한다. 

     

    AVAudioRecorder updateMeter() 함수 사용 

    타이머를 걸어서 0.1 초 마다 audioRecorder 의 updateMeter() 함수를 호출 후 averagePower, peakPower 를 구한다. 

    // 0.1 초 짜리 timer 
    var recordingTimer = Timer.publish(every: 0.1, on: .main, in: .common)
    ...
    audioRecorder.isMeteringEnabled = true
    ...
    }.onReceive(audioRecorder.recordingTimer) { time in
    	audioRecorder.updateMeter()
        
        let averagePower = audioRecorder.averagePower(forChannel: 0)
        let peakPower = audioRecorder.peakPower(forChannel: 0)
    }
    ..
    
    

    averagePower, PeakPower Apple Document 

    developer.apple.com/documentation/avfoundation/avaudioplayer/1390838-averagepower

    developer.apple.com/documentation/avfoundation/avaudiorecorder/1389463-peakpower

     

    Return Value of averagePower(forChannel:)

    A floating-point representation, in decibels, of a given audio channel’s current average power. A return value of 0 dB indicates full scale, or maximum power; a return value of –160 dB indicates minimum power (that is, near silence).

    If the signal provided to the audio player exceeds ±full scale, then the return value may exceed 0 (that is, it may enter the positive range).

     

    위 설명에 나와있듯이 averagePower라고 나온 값은 -160 에서 0 사이의 값이 나온다. 그런데 실제로 녹음을 해 보면 white noise 때문인지 아무말도 하고 있지 않을 때 -50 정도로 측정된다. 말을 하고 있을때는 약 -10 정도. 그래서 ProgressBar에 예쁘게 보여주려면 한 번 noramlize 과정을 거쳐야 한다. 

     

    // refer to https://medium.com/swlh/swiftui-create-a-sound-visualizer-cadee0b6ad37
        private func normalizeSoundLevel(level: Float) -> Float {
            // 화면에 표시되는 rawSoundLevel 기준
            // white noise만 존재할 때의 값을 lowLevel 에 할당
            // 가장 큰 소리를 냈을 때 값을 highLevel 에 할당
            
            let lowLevel: Float = -50
            let highLevel: Float = -10
            
            var level = max(0.0, level - lowLevel) // low level이 0이 되도록 shift
            level = min(level, highLevel - lowLevel) // high level 도 shift
            // 이제 level은 0.0 ~ 40까지의 값으로 설정 됨.
            return level / (highLevel - lowLevel) // scaled to 0.0 ~ 1
        }

     

    위와 같이 작성했을 때 0~1 사이에 괜찮은 값이 나왔다. 핸드폰 기종이나 주면 환경에 따라서 추후에 수치를 조절할 필요가 있을 것 같다. 

    참고한 아티클: medium.com/swlh/swiftui-create-a-sound-visualizer-cadee0b6ad37

     

    SwiftUI: Create a Sound Visualizer.

    Using the built in microphone, sample the sound level in db to visualize the it in SwiftUI.

    medium.com

     

    반응형
    저작자표시 비영리 변경금지 (새창열림)

    '개발' 카테고리의 다른 글

    CocoaPod 여러가지  (0) 2021.02.09
    [Swift/iOS] Alamofire & Combine 조합으로 네트워크 레이어 만들기  (1) 2021.01.22
    Ruby path 다시 설정하기  (0) 2020.11.30
    [Xcode] Device Build, Archive 안되는 이슈 CodeSign error: unknown error -26276 해결 방법  (0) 2020.11.27
    [iOS] Combine-Realm 에서 item 삭제시 crash 이슈 해결  (0) 2020.11.19

    댓글

    관련글

    • CocoaPod 여러가지 2021.02.09
    • [Swift/iOS] Alamofire & Combine 조합으로 네트워크 레이어 만들기 2021.01.22
    • Ruby path 다시 설정하기 2020.11.30
    • [Xcode] Device Build, Archive 안되는 이슈 CodeSign error: unknown error -26276 해결 방법 2020.11.27
    맨 위로
전체 글 보기
Tistory 로그인
Tistory 로그아웃
로그아웃 글쓰기 관리

Today

Total

Powered by ⓒ Kakao Corp.

Designed by Nana
블로그 이미지
dundin

티스토리툴바