diff --git a/RNSound/RNSound.h b/RNSound/RNSound.h index 63a1f449..3060c508 100644 --- a/RNSound/RNSound.h +++ b/RNSound/RNSound.h @@ -7,5 +7,5 @@ #import @interface RNSound : NSObject - +@property (nonatomic, weak) NSNumber* _key; @end diff --git a/RNSound/RNSound.m b/RNSound/RNSound.m index ce7ae430..5b8d63a1 100644 --- a/RNSound/RNSound.m +++ b/RNSound/RNSound.m @@ -11,6 +11,31 @@ @implementation RNSound { NSMutableDictionary* _callbackPool; } +@synthesize _key = _key; + +- (void)audioSessionChangeObserver:(NSNotification *)notification{ + NSDictionary* userInfo = notification.userInfo; + AVAudioSessionRouteChangeReason audioSessionRouteChangeReason = [userInfo[@"AVAudioSessionRouteChangeReasonKey"] longValue]; + AVAudioSessionInterruptionType audioSessionInterruptionType = [userInfo[@"AVAudioSessionInterruptionTypeKey"] longValue]; + AVAudioPlayer* player = [self playerForKey:self._key]; + //if (audioSessionRouteChangeReason == AVAudioSessionRouteChangeReasonNewDeviceAvailable){ + // NSLog(@"in"); + //} + //if (audioSessionInterruptionType == AVAudioSessionInterruptionTypeEnded){ + // Resumed? + //} + if (audioSessionRouteChangeReason == AVAudioSessionRouteChangeReasonOldDeviceUnavailable){ + if (player) { + [player pause]; + } + } + if (audioSessionInterruptionType == AVAudioSessionInterruptionTypeBegan){ + if (player) { + [player pause]; + } + } +} + -(NSMutableDictionary*) playerPool { if (!_playerPool) { _playerPool = [NSMutableDictionary new]; @@ -181,6 +206,9 @@ -(NSDictionary *)constantsToExport { } RCT_EXPORT_METHOD(play:(nonnull NSNumber*)key withCallback:(RCTResponseSenderBlock)callback) { + [[AVAudioSession sharedInstance] setActive:YES error:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionChangeObserver:) name:AVAudioSessionRouteChangeNotification object:nil]; + self._key = key; AVAudioPlayer* player = [self playerForKey:key]; if (player) { [[self callbackPool] setObject:[callback copy] forKey:key]; @@ -211,6 +239,8 @@ -(NSDictionary *)constantsToExport { [player stop]; [[self callbackPool] removeObjectForKey:player]; [[self playerPool] removeObjectForKey:key]; + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + [notificationCenter removeObserver:self]; } }