我看到您正在使用MPMediaPlayer框架,但麥克風處理是使用AVAudioPlayer框架完成的,您需要將該框架添加到您的項目中。
蘋果網站的代碼來自AVAudioPlayer框架,我用它來處理用戶插入或移除蘋果麥克風耳機的干擾。
看看蘋果的iPhone Dev Center Audio Session Programming Guide。
- (void) beginInterruption {
if (playing) {
playing = NO;
interruptedWhilePlaying = YES;
[self updateUserInterface];
}
}
NSError *activationError = nil;
- (void) endInterruption {
if (interruptedWhilePlaying) {
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
[player play];
playing = YES;
interruptedWhilePlaying = NO;
[self updateUserInterface];
}
}
我的代碼是有點不同的,一些本可以幫助你:
void interruptionListenerCallback (
void *inUserData,
UInt32 interruptionState
) {
// This callback, being outside the implementation block, needs a reference
// to the AudioViewController object
RecordingListViewController *controller = (RecordingListViewController *) inUserData;
if (interruptionState == kAudioSessionBeginInterruption) {
//NSLog (@"Interrupted. Stopping playback or recording.");
if (controller.audioRecorder) {
// if currently recording, stop
[controller recordOrStop: (id) controller];
} else if (controller.audioPlayer) {
// if currently playing, pause
[controller pausePlayback];
controller.interruptedOnPlayback = YES;
}
} else if ((interruptionState == kAudioSessionEndInterruption) && controller.interruptedOnPlayback) {
// if the interruption was removed, and the app had been playing, resume playback
[controller resumePlayback];
controller.interruptedOnPlayback = NO;
}
}
void recordingListViewMicrophoneListener (
void *inUserData,
AudioSessionPropertyID inPropertyID,
UInt32 inPropertyValueSize,
const void *isMicConnected
) {
// ensure that this callback was invoked for a change to microphone connection
if (inPropertyID != kAudioSessionProperty_AudioInputAvailable) {
return;
}
RecordingListViewController *controller = (RecordingListViewController *) inUserData;
// kAudioSessionProperty_AudioInputAvailable is a UInt32 (see Apple Audio Session Services Reference documentation)
// to read isMicConnected, convert the const void pointer to a UInt32 pointer
// then dereference the memory address contained in that pointer
UInt32 connected = * (UInt32 *) isMicConnected;
if (connected){
[controller setMicrophoneConnected : YES];
}
else{
[controller setMicrophoneConnected: NO];
}
// check to see if microphone disconnected while recording
// cancel the recording if it was
if(controller.isRecording && !connected){
[controller cancelDueToMicrophoneError];
}
}
ERM 1)wat的inPropertyValue?它不會在方法參數 中刪除2)CFDictionaryGetValue返回一個無法與CFNumberRef匹配的void指針。在返回值之前,我需要做任何投射嗎? – 2009-12-04 03:26:22
嗯我設法編譯我的代碼,一切運行良好,但是當我插入或拔掉我的耳機沒有任何反應。 audioRouteChangeListenerCallback函數未被調用。在上面的函數旁邊還有其他的東西嗎? – 2009-12-04 08:30:12
你應該在你的調用初始化AudioSession之後註冊監聽器函數..你是這麼做的嗎? – prakash 2009-12-04 09:17:50