3
我在我的iOS應用中遇到了音量問題。當我撥打setupMic()
時,整個應用的音量水平顯着降低。
這裏是我使用的代碼:訪問麥克風後,整個應用的音量變得更低噪音
func setupMic() {
//make an AudioSession, set it to PlayAndRecord and make it active
let audioSession: AVAudioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch {
print("There was an error setting the category")
}
do {
try audioSession.setActive(true)
} catch {
print("There was an error setting the audio session to active")
}
//set up the URL for the audio file
let documents: AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let str = documents.stringByAppendingPathComponent("recordTest.caf")
let url = NSURL.fileURLWithPath(str as String)
//make a dictionary to hold the recording setting so we can instantiate our AVAudioRecorder
let number = NSNumber(unsignedInt: kAudioFormatAppleIMA4)
let recordSettings: [String: AnyObject] = [AVFormatIDKey: number,
AVSampleRateKey: 44100.0,
AVNumberOfChannelsKey: 2,
AVEncoderBitRateKey: 12800,
AVLinearPCMBitDepthKey: 16,
AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue]
//Instantiate an AVAudioRecorder
do {
recorder = try AVAudioRecorder(URL: url, settings: recordSettings)
} catch {
print("There was an error")
}
}
//This function is called everytime our timer levelTimer fires
func levelTimerCallback() {
recorder.updateMeters()
let averagePower = self.recorder.peakPowerForChannel(0)
if averagePower > -7 {
stopMonitoring()
print(recorder.peakPowerForChannel(0))
didCompleteChallenge(true)
}
}
func startMonitoring() {
if self.recorder != nil {
recorder.prepareToRecord()
recorder.meteringEnabled = true
//start recording
recorder.record()
//instantiate a timer to be called with whatever frequency we want to grab metering values
self.levelTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(levelTimerCallback), userInfo: nil, repeats: true)
}
}
func stopMonitoring() {
self.recorder.stop()
self.recorder.deleteRecording()
self.levelTimer.invalidate()
}
我打電話setupMic()
和startMonitoring()
在updateWith()
方法。當視圖更新爲updateWith()
時,我還會撥打stopMonitoring()
一旦麥克風被訪問,音量就會下降。有什麼建議麼?任何修復?
我設置了這個類別,但是當我插上耳機時,我知道只有一面有聲音,另一面不能工作,有什麼線索? –
謝謝@Cameron,投票,它爲我工作 –