Sound.m 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #import "Sound.h"
  2. @interface PlayDelegate : CallbackDelegate <NSSoundDelegate> {
  3. }
  4. @property (nonatomic, weak) Sound *sound;
  5. - (id) initWithContext:(JSContextRef)aContext
  6. forCallback:(WebScriptObject*)aCallback
  7. withSound:(Sound*)aSound;
  8. @end
  9. @implementation PlayDelegate
  10. @synthesize sound;
  11. - (id) initWithContext:(JSContextRef)aContext
  12. forCallback:(WebScriptObject*)aCallback
  13. withSound:(Sound*)aSound
  14. {
  15. self = [super initWithContext:aContext forCallback:aCallback];
  16. if (!self)
  17. return nil;
  18. sound = aSound;
  19. return self;
  20. }
  21. - (void)sound:(NSSound *)aSound didFinishPlaying:(BOOL)finishedPlaying {
  22. [self callWithParams:[aSound name], nil];
  23. [sound.pending removeObject:self];
  24. }
  25. @end
  26. @implementation Sound
  27. @synthesize pending;
  28. - (id) initWithContext:(JSContextRef)aContext {
  29. self = [super initWithContext:aContext];
  30. if (!self) {
  31. return nil;
  32. }
  33. pending = [NSMutableSet new];
  34. return self;
  35. }
  36. - (void) playSound:(NSSound*)sound onComplete:(WebScriptObject*)callback {
  37. if (callback != (id)[WebUndefined undefined]) {
  38. PlayDelegate *d = [[PlayDelegate alloc] initWithContext:context
  39. forCallback:callback
  40. withSound:self];
  41. [pending addObject:d];
  42. [sound setDelegate:d];
  43. }
  44. [sound play];
  45. }
  46. - (void) play:(NSString*)file onComplete:(WebScriptObject*)callback {
  47. NSURL* fileUrl = [NSURL fileURLWithPath:[[Utils sharedInstance] pathForResource:file]];
  48. DebugNSLog(@"Sound file:%@", [fileUrl description]);
  49. NSSound* sound = [[NSSound alloc] initWithContentsOfURL:fileUrl byReference:YES];
  50. [self playSound:sound onComplete:callback];
  51. }
  52. - (void) playSystem:(NSString*)name onComplete:(WebScriptObject*)callback {
  53. NSSound *systemSound = [NSSound soundNamed:name];
  54. [self playSound:systemSound onComplete:callback];
  55. }
  56. #pragma mark WebScripting Protocol
  57. + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
  58. return [self webScriptNameForSelector:selector] == nil;
  59. }
  60. + (BOOL) isKeyExcludedFromWebScript:(const char*)name {
  61. return YES;
  62. }
  63. + (NSString*) webScriptNameForSelector:(SEL)selector {
  64. id result = nil;
  65. if (selector == @selector(play:onComplete:)) {
  66. result = @"play";
  67. }
  68. else if (selector == @selector(playSystem:onComplete:)) {
  69. result = @"playSystem";
  70. }
  71. return result;
  72. }
  73. @end