Skip to content

Commit

Permalink
Pause when I put out headphone plug from the device or get called.
Browse files Browse the repository at this point in the history
  • Loading branch information
kurokky_mac authored and kurokky_mac committed Oct 7, 2017
1 parent a6ca0d2 commit ab7389c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
2 changes: 1 addition & 1 deletion RNSound/RNSound.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
#import <AVFoundation/AVFoundation.h>

@interface RNSound : NSObject <RCTBridgeModule, AVAudioPlayerDelegate>

@property (nonatomic, weak) NSNumber* _key;
@end
30 changes: 30 additions & 0 deletions RNSound/RNSound.m
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down Expand Up @@ -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];
Expand Down Expand Up @@ -211,6 +239,8 @@ -(NSDictionary *)constantsToExport {
[player stop];
[[self callbackPool] removeObjectForKey:player];
[[self playerPool] removeObjectForKey:key];
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self];
}
}

Expand Down

0 comments on commit ab7389c

Please sign in to comment.