iOS Question Play sound on notification

Nicolás Cieri

Active Member
Licensed User
Hi,

I want to play an mp3 in the background when receiving a notification.
Apparently I have everything well configured .. only that sometimes it works and sometimes it doesn't.

This code is on... Application_RemoteNotification

The notification is received (I can see in log), but sometimes the sound does not play.

B4X:
            Try
                CompletionHandler.Complete
                Dim nm As String = Message.Get("nm")
                spp.toastMessage(nm & " " & "has sent you an alert!")
                MediaPlayer1.Initialize(File.DirAssets,"Alert.mp3","")
                MediaPlayer1.Looping=False
                MediaPlayer1.Volume=1
                MediaPlayer1.Position=0
                MediaPlayer1.Play
                NativeMe.RunMethod("register", Null)
            Catch
                Log(LastException)
            End Try

I've even gone through all the steps so it can play in the background...

B4X:
#If OBJC
@import MediaPlayer;
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
- (void)setAudioSession {
  AVAudioSession *audioSession = [AVAudioSession sharedInstance];
  NSError *err = nil;
  BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&err];
  if (success) {
     success = [audioSession setActive:YES error:&err];
   success = [audioSession setPreferredSampleRate:4096 error:nil];
   [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  }
  if (!success)
  [NSException raise:@"" format:@"Error setting audio session: %@", err];
}
- (void)register {
   MPRemoteCommandCenter* center = [MPRemoteCommandCenter sharedCommandCenter];
   center.playCommand.enabled = true;
   center.pauseCommand.enabled = true;
   [center.playCommand addTarget:self action:@selector(play)];
   [center.pauseCommand addTarget:self action:@selector(pause)];
}
- (MPRemoteCommandHandlerStatus) play {
   NSLog(@"test");
   [self.bi raiseEvent:nil event:@"controlevent:"  params:@[@"play"]];
   return MPRemoteCommandHandlerStatusSuccess;

}
- (MPRemoteCommandHandlerStatus) pause {
   [self.bi raiseEvent:nil event:@"controlevent:"  params:@[@"pause"]];
   return MPRemoteCommandHandlerStatusSuccess;
}

#end if
 
Top