-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathRNSoundPlayer.m
266 lines (231 loc) · 8.28 KB
/
RNSoundPlayer.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
//
// RNSoundPlayer
//
// Created by Johnson Su on 2018-07-10.
//
#import "RNSoundPlayer.h"
#import <AVFoundation/AVFoundation.h>
@implementation RNSoundPlayer
{
bool hasListeners;
}
static NSString *const EVENT_SETUP_ERROR = @"OnSetupError";
static NSString *const EVENT_FINISHED_LOADING = @"FinishedLoading";
static NSString *const EVENT_FINISHED_LOADING_FILE = @"FinishedLoadingFile";
static NSString *const EVENT_FINISHED_LOADING_URL = @"FinishedLoadingURL";
static NSString *const EVENT_FINISHED_PLAYING = @"FinishedPlaying";
RCT_EXPORT_MODULE();
@synthesize bridge = _bridge;
+ (BOOL)requiresMainQueueSetup {
return YES;
}
- (instancetype)init {
self = [super init];
if (self) {
self.loopCount = 0;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(itemDidFinishPlaying:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:nil];
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (NSArray<NSString *> *)supportedEvents {
return @[EVENT_FINISHED_PLAYING, EVENT_FINISHED_LOADING, EVENT_FINISHED_LOADING_URL, EVENT_FINISHED_LOADING_FILE, EVENT_SETUP_ERROR];
}
-(void)startObserving {
hasListeners = YES;
}
-(void)stopObserving {
hasListeners = NO;
}
RCT_EXPORT_METHOD(playUrl:(NSString *)url) {
[self prepareUrl:url];
if (self.avPlayer) {
[self.avPlayer play];
}
}
RCT_EXPORT_METHOD(loadUrl:(NSString *)url) {
[self prepareUrl:url];
}
RCT_EXPORT_METHOD(playSoundFile:(NSString *)name ofType:(NSString *)type) {
[self mountSoundFile:name ofType:type];
if (self.player) {
[self.player play];
}
}
RCT_EXPORT_METHOD(playSoundFileWithDelay:(NSString *)name ofType:(NSString *)type delay:(double)delay) {
[self mountSoundFile:name ofType:type];
if (self.player) {
[self.player playAtTime:(self.player.deviceCurrentTime + delay)];
}
}
RCT_EXPORT_METHOD(loadSoundFile:(NSString *)name ofType:(NSString *)type) {
[self mountSoundFile:name ofType:type];
}
RCT_EXPORT_METHOD(pause) {
if (self.player != nil) {
[self.player pause];
}
if (self.avPlayer != nil) {
[self.avPlayer pause];
}
}
RCT_EXPORT_METHOD(resume) {
if (self.player != nil) {
[self.player play];
}
if (self.avPlayer != nil) {
[self.avPlayer play];
}
}
RCT_EXPORT_METHOD(stop) {
if (self.player != nil) {
[self.player stop];
}
if (self.avPlayer != nil) {
[self.avPlayer pause];
[self.avPlayer seekToTime:kCMTimeZero];
}
}
RCT_EXPORT_METHOD(seek:(float)seconds) {
if (self.player != nil) {
self.player.currentTime = seconds;
}
if (self.avPlayer != nil) {
[self.avPlayer seekToTime:CMTimeMakeWithSeconds(seconds, NSEC_PER_SEC)];
}
}
#if !TARGET_OS_TV
RCT_EXPORT_METHOD(setSpeaker:(BOOL)on) {
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *error = nil;
if (on) {
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
[session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];
} else {
[session setCategory:AVAudioSessionCategoryPlayback error:&error];
[session overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:&error];
}
[session setActive:YES error:&error];
if (error) {
[self sendErrorEvent:error];
}
}
#endif
RCT_EXPORT_METHOD(setMixAudio:(BOOL)on) {
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *error = nil;
if (on) {
[session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&error];
} else {
[session setCategory:AVAudioSessionCategoryPlayback withOptions:0 error:&error];
}
[session setActive:YES error:&error];
if (error) {
[self sendErrorEvent:error];
}
}
RCT_EXPORT_METHOD(setVolume:(float)volume) {
if (self.player != nil) {
[self.player setVolume:volume];
}
if (self.avPlayer != nil) {
[self.avPlayer setVolume:volume];
}
}
RCT_EXPORT_METHOD(setNumberOfLoops:(NSInteger)loopCount) {
self.loopCount = loopCount;
if (self.player != nil) {
[self.player setNumberOfLoops:loopCount];
}
}
RCT_REMAP_METHOD(getInfo,
getInfoWithResolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
if (self.player != nil) {
NSDictionary *data = @{
@"currentTime": [NSNumber numberWithDouble:[self.player currentTime]],
@"duration": [NSNumber numberWithDouble:[self.player duration]]
};
resolve(data);
} else if (self.avPlayer != nil) {
CMTime currentTime = [[self.avPlayer currentItem] currentTime];
CMTime duration = [[[self.avPlayer currentItem] asset] duration];
NSDictionary *data = @{
@"currentTime": [NSNumber numberWithFloat:CMTimeGetSeconds(currentTime)],
@"duration": [NSNumber numberWithFloat:CMTimeGetSeconds(duration)]
};
resolve(data);
} else {
resolve(nil);
}
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
if (hasListeners) {
[self sendEventWithName:EVENT_FINISHED_PLAYING body:@{@"success": [NSNumber numberWithBool:flag]}];
}
}
- (void)itemDidFinishPlaying:(NSNotification *)notification {
if (hasListeners) {
[self sendEventWithName:EVENT_FINISHED_PLAYING body:@{@"success": [NSNumber numberWithBool:YES]}];
}
}
- (void)mountSoundFile:(NSString *)name ofType:(NSString *)type {
if (self.avPlayer) {
self.avPlayer = nil;
}
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:name ofType:type];
if (soundFilePath == nil) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
soundFilePath = [NSString stringWithFormat:@"%@.%@", [documentsDirectory stringByAppendingPathComponent:name], type];
}
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSError *error = nil;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:&error];
if (error) {
[self sendErrorEvent:error];
return;
}
[self.player setDelegate:self];
[self.player setNumberOfLoops:self.loopCount];
[self.player prepareToPlay];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
if (error) {
[self sendErrorEvent:error];
return;
}
if (hasListeners) {
[self sendEventWithName:EVENT_FINISHED_LOADING body:@{@"success": [NSNumber numberWithBool:YES]}];
[self sendEventWithName:EVENT_FINISHED_LOADING_FILE body:@{@"success": [NSNumber numberWithBool:YES], @"name": name, @"type": type}];
}
}
- (void)prepareUrl:(NSString *)url {
if (self.player) {
self.player = nil;
}
NSURL *soundURL = [NSURL URLWithString:url];
self.avPlayer = [[AVPlayer alloc] initWithURL:soundURL];
[self.avPlayer.currentItem addObserver:self forKeyPath:@"status" options:0 context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if (object == self.avPlayer.currentItem && [keyPath isEqualToString:@"status"] && hasListeners) {
if (self.avPlayer.currentItem.status == AVPlayerItemStatusReadyToPlay) {
[self sendEventWithName:EVENT_FINISHED_LOADING body:@{@"success": [NSNumber numberWithBool:YES]}];
NSURL *url = [(AVURLAsset *)self.avPlayer.currentItem.asset URL];
[self sendEventWithName:EVENT_FINISHED_LOADING_URL body:@{@"success": [NSNumber numberWithBool:YES], @"url": [url absoluteString]}];
} else if (self.avPlayer.currentItem.status == AVPlayerItemStatusFailed) {
[self sendErrorEvent:self.avPlayer.currentItem.error];
}
}
}
- (void)sendErrorEvent:(NSError *)error {
if (hasListeners) {
[self sendEventWithName:EVENT_SETUP_ERROR body:@{@"error": [error localizedDescription]}];
}
}
@end