iPhone에서 이어 피스를 프로그래밍 방식으로 감지하는 방법은 무엇입니까?
-
11-09-2019 - |
문제
현재 앱 내부의 iPhone Music Library에서 음악을 재생하는 프로젝트를 진행하고 있습니다. MPMediaPickerController를 사용하여 사용자가 음악을 선택하고 iPhone 내 iPod Music Player를 사용하여 재생할 수 있습니다.
그러나 사용자가 이어 피스를 삽입하고 제거 할 때 문제가 발생했습니다. 음악은 갑자기 아무 이유없이 연주를 중단 할 것입니다. 약간의 테스트 후, 나는 사용자가 장치에서 이어 피스를 뽑을 때 iPod 플레이어가 재생을 일시 중지한다는 것을 알았습니다. 음악 재생을 재개 할 수 있도록 이어 피스가 플러그를 뽑았는지 프로그래밍 방식으로 감지 할 수있는 방법이 있습니까? 아니면 사용자가 이어 피스를 뽑을 때 iPod 플레이어가 일시 중지되는 것을 방지하는 방법이 있습니까?
해결책
AUDIOROUTE 변경 사항에 등록하고 ROUT 변경 사항을 처리하는 방법을 구현해야합니다.
// Registers the audio route change listener callback function
AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange,
audioRouteChangeListenerCallback,
self);
콜백 내에서 경로 변경 이유를 얻을 수 있습니다.
CFDictionaryRef routeChangeDictionary = inPropertyValue;
CFNumberRef routeChangeReasonRef =
CFDictionaryGetValue (routeChangeDictionary,
CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
SInt32 routeChangeReason;
CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
{
// Headset is unplugged..
}
if (routeChangeReason == kAudioSessionRouteChangeReason_NewDeviceAvailable)
{
// Headset is plugged in..
}
다른 팁
경로 변경을 듣지 않고 헤드폰이 주어진 시간에 연결되어 있는지 확인하려면 다음을 수행 할 수 있습니다.
OSStatus error = AudioSessionInitialize(NULL, NULL, NULL, NULL);
if (error)
NSLog("Error %d while initializing session", error);
UInt32 routeSize = sizeof (CFStringRef);
CFStringRef route;
error = AudioSessionGetProperty (kAudioSessionProperty_AudioRoute,
&routeSize,
&route);
if (error)
NSLog("Error %d while retrieving audio property", error);
else if (route == NULL) {
NSLog(@"Silent switch is currently on");
} else if([route isEqual:@"Headset"]) {
NSLog(@"Using headphones");
} else {
NSLog(@"Using %@", route);
}
건배, 라파 엘로 콜라 산테
MPMediaPlayer 프레임 워크를 사용하고 있지만 마이크 처리는 Avaudioplayer 프레임 워크를 사용하여 수행되며 프로젝트에 추가해야합니다.
Apple의 웹 사이트에는 Avaudioplayer 프레임 워크의 코드가 있으며 Apple 마이크 헤드폰을 연결하거나 제거하는 사용자의 중단을 처리하는 데 사용합니다.
Apple 's를 확인하십시오 iPhone Dev Center 오디오 세션 프로그래밍 안내서.
- (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];
}
}
안녕하세요 여러분은 AddMusic 샘플 앱을 확인합니다. 모든 iPod 관련 문제를 해결합니다
먼저 다음 코드로 알림을 위해 iPod 플레이어를 등록하십시오
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter
addObserver: self
selector: @selector (handle_PlaybackStateChanged:)
name: MPMusicPlayerControllerPlaybackStateDidChangeNotification
object: musicPlayer];
[musicPlayer beginGeneratingPlaybackNotifications];
알림에서 다음 코드를 구현하십시오
- (void) handle_PlaybackStateChanged: (id) notification
{
MPMusicPlaybackState playbackState = [musicPlayer playbackState];
if (playbackState == MPMusicPlaybackStatePaused)
{
[self playiPodMusic];
}
else if (playbackState == MPMusicPlaybackStatePlaying)
{
}
else if (playbackState == MPMusicPlaybackStateStopped)
{
[musicPlayer stop];
}
}