Skip to content

Instantly share code, notes, and snippets.

@hkitago
Created July 26, 2023 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hkitago/4701e109290c21a05da04bee2763dc3c to your computer and use it in GitHub Desktop.
Save hkitago/4701e109290c21a05da04bee2763dc3c to your computer and use it in GitHub Desktop.
Smartphone dB Measurement for SwiftUI
//
// ContentView.swift
// audioRecorder
//
// Created by Hiroyuki KITAGO and ChatGPT July 20 Version on 2023/07/26.
//
import SwiftUI
import AVFoundation
struct ContentView: View {
@State private var volume: Double = 0.0
@State private var audioRecorder: AVAudioRecorder!
var body: some View {
VStack {
Text("音量測定アプリ")
.font(.title)
.padding()
Text(String(format: "音量: %.2f", volume))
.font(.headline)
.padding()
Spacer()
Button(action: {
// マイクのアクセス許可を確認
requestMicrophonePermission()
}) {
Text("マイクにアクセス")
.font(.headline)
.foregroundColor(.white)
.padding()
.background(Color.blue)
.cornerRadius(10)
}
}
}
func requestMicrophonePermission() {
AVAudioSession.sharedInstance().requestRecordPermission { granted in
DispatchQueue.main.async {
if granted {
// マイクへのアクセスが許可された場合、マイクをセットアップ
setupMicrophone()
} else {
// マイクへのアクセスが拒否された場合、エラーを表示
print("マイクへのアクセスが拒否されました。")
}
}
}
}
func setupMicrophone() {
let session = AVAudioSession.sharedInstance()
do {
// セッションのカテゴリをレコードに設定
try session.setCategory(.record, mode: .default)
// セッションをアクティブにする
try session.setActive(true)
// 音量を取得するための設定
let settings = [
AVFormatIDKey: kAudioFormatAppleLossless,
AVSampleRateKey: 44100.0,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue
] as [String : Any]
// 録音オブジェクトを作成
audioRecorder = try AVAudioRecorder(url: URL(fileURLWithPath: "/dev/null"), settings: settings)
// 音量メーターを有効にする
audioRecorder.isMeteringEnabled = true
// 録音を開始
audioRecorder.prepareToRecord()
audioRecorder.record()
// 定期的に音量を更新するタイマーを設定
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
self.updateVolume()
}
} catch {
print("マイクのセットアップに失敗しました。")
}
}
func updateVolume() {
// 音量を更新する
audioRecorder.updateMeters()
// デシベル値を取得
let decibels = audioRecorder.averagePower(forChannel: 0)
// デシベル値を0から1の範囲に変換
let normalizedVolume = pow(10, (decibels / 20))
// ステート変数に反映(Doubleに変換してから代入)
volume = Double(normalizedVolume)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment