Beispiel #1
0
        public void Generate(bool?useSpeakerMode = null)
        {
            AudioAttributes aa;
            int             SessionID = SFX.audioManager.GenerateAudioSessionId();

            if (Res.AllowSpeakerSounds)
            {
                _useSpeakerMode = useSpeakerMode ?? _useSpeakerMode;
            }
            else
            {
                _useSpeakerMode = false;
            }

            if (_useSpeakerMode)
            {
                aa = new AudioAttributes.Builder()
                     .SetUsage(AudioUsageKind.NotificationRingtone)
                     .Build();
                //SessionID = SFX.SessionIDSpeakers;
            }
            else
            {
                aa = new AudioAttributes.Builder()
                     .SetUsage(AudioUsageKind.Unknown)
                     .Build();
                //SessionID = SFX.SessionIDHeadphones;
            }

            lock (__syncRoot)
            {
                __innerEffect = MediaPlayer.Create(Application.Context, _resourceID, aa, SessionID);
            }
            SFX.NumberOfMediaPlayersCreated++;
        }
Beispiel #2
0
    private void initPlayer()
    {
        Encoding encoding = Encoding.Pcm16bit;

        // Prepare player
        AudioAttributes aa = new AudioAttributes.Builder()
                             .SetContentType(AudioContentType.Speech)
                             .SetLegacyStreamType(Stream.VoiceCall)
                             .SetFlags(AudioFlags.LowLatency)
                             .SetUsage(AudioUsageKind.VoiceCommunication)
                             .Build();

        AudioFormat af = new AudioFormat.Builder()
                         .SetSampleRate(44100)
                         .SetChannelMask(ChannelOut.Mono)
                         .SetEncoding(encoding)
                         .Build();

        bufferSize = AudioTrack.GetMinBufferSize(44100, ChannelOut.Mono, encoding) * 10;

        audioPlayer = new AudioTrack(aa, af, bufferSize, AudioTrackMode.Stream, 0);

        // TODO implement dynamic volume control
        AudioManager am = (AudioManager)MainActivity.Instance.GetSystemService(Context.AudioService);

        audioPlayer.SetVolume(am.GetStreamVolume(Stream.VoiceCall));

        audioPlayer.Play();
    }
Beispiel #3
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.activity_alarm);
            Window.AddFlags(WindowManagerFlags.KeepScreenOn |
                            WindowManagerFlags.DismissKeyguard |
                            WindowManagerFlags.ShowWhenLocked |
                            WindowManagerFlags.TurnScreenOn);

            Title = GetString(Resource.String.alarm_title).Replace("/NAME/", alarmTarget.DisplayName);

            var textview = FindViewById <TextView>(Resource.Id.titleTextView);

            textview.Text = Title;

            var button = FindViewById <Button>(Resource.Id.ok_button);

            button.Click += Button_Click;

            try
            {
                var builder = new AudioAttributes.Builder();
                builder.SetContentType(AudioContentType.Music);
                builder.SetUsage(AudioUsageKind.Alarm);
                alarmPlayer.SetAudioAttributes(builder.Build());
                alarmPlayer.SetDataSource(ApplicationContext, Uri.Parse(alarmTarget.NotifySoundPath));
                alarmPlayer.Looping = true;
                alarmPlayer.Prepare();
                alarmPlayer.Start();
            }
            catch
            {
            }
        }
        void CreateNotificationChannel2()
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                // Notification channels are new in API 26 (and not a part of the
                // support library). There is no need to create a notification
                // channel on older versions of Android.
                return;
            }
            Android.Net.Uri alarmUri = Android.Net.Uri.Parse($"{ ContentResolver.SchemeAndroidResource}://{PackageName}/{Resource.Raw.MyRingTone}");

            var alarmAttributes = new AudioAttributes.Builder()
                                  .SetContentType(AudioContentType.Sonification)
                                  .SetUsage(AudioUsageKind.Notification).Build();
            var name        = Resources.GetString(Resource.String.channel_name2);
            var description = GetString(Resource.String.channel_description);
            var channel     = new NotificationChannel(CHANNEL_ID2, name, NotificationImportance.Low)
            {
                Description = description
            };

            channel.SetSound(alarmUri, alarmAttributes);
            channel.SetVibrationPattern(new long[] { 1000, 1000 });


            var notificationManager2 = (NotificationManager)GetSystemService(NotificationService);

            notificationManager2.CreateNotificationChannel(channel);
        }
Beispiel #5
0
        /// <summary>
        /// Create Notification Channel when API >= 26.
        /// </summary>
        /// <param name="request"></param>
        public static bool CreateNotificationChannel(NotificationChannelRequest request = null)
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                return(false);
            }

            if (Application.Context.GetSystemService(Context.NotificationService) is not NotificationManager
                notificationManager)
            {
                return(false);
            }

            request ??= new NotificationChannelRequest();

            if (string.IsNullOrWhiteSpace(request.Name))
            {
                request.Name = "General";
            }

            if (string.IsNullOrWhiteSpace(request.Id))
            {
                request.Id = DefaultChannelId;
            }

            // you can't change the importance or other notification behaviors after this.
            // once you create the channel, you cannot change these settings and
            // the user has final control of whether these behaviors are active.
            using var channel = new NotificationChannel(request.Id, request.Name, request.Importance)
                  {
                      Description          = request.Description,
                      Group                = request.Group,
                      LightColor           = request.LightColor,
                      LockscreenVisibility = request.LockScreenVisibility,
                  };
            var soundUri = GetSoundUri(request.Sound);

            if (soundUri != null)
            {
                using var audioAttributesBuilder = new AudioAttributes.Builder();
                var audioAttributes = audioAttributesBuilder.SetUsage(AudioUsageKind.Notification)
                                      ?.SetContentType(AudioContentType.Music)
                                      ?.Build();
                channel.SetSound(soundUri, audioAttributes);
            }

            if (request.VibrationPattern != null)
            {
                channel.SetVibrationPattern(request.VibrationPattern);
            }

            channel.SetShowBadge(request.ShowBadge);
            channel.EnableLights(request.EnableLights);
            channel.EnableVibration(request.EnableVibration);
            channel.SetBypassDnd(request.CanBypassDnd);

            notificationManager.CreateNotificationChannel(channel);

            return(true);
        }
Beispiel #6
0
        void CreateNotificationChannel()
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                // Notification channels are new in API 26 (and not a part of the
                // support library). There is no need to create a notification
                // channel on older versions of Android.
                return;
            }

            var alarmAttributes = new AudioAttributes.Builder()
                                  .SetContentType(AudioContentType.Sonification)
                                  .SetUsage(AudioUsageKind.Notification).Build();

            // Create the uri for the alarm file
            Android.Net.Uri alarmUri = Android.Net.Uri.Parse($"{ContentResolver.SchemeAndroidResource}://{Application.Context.PackageName}/{Resource.Raw.soundfile}");

            var channel = new NotificationChannel(CHANNEL_ID, "SelfTrackerNotificationChannel", NotificationImportance.Default)
            {
                Description = "Notification Channel"
            };
            //channel.SetSound(alarmUri, alarmAttributes);

            var notificationManager = (NotificationManager)GetSystemService(NotificationService);

            notificationManager.CreateNotificationChannel(channel);
        }
Beispiel #7
0
        static AudioService()
        {
            var alarmPath        = P42.Utils.EmbeddedResourceCache.LocalStorageFullPathForEmbeddedResource("Forms9Patch.Resources.Sounds.alarm.ogg", typeof(Forms9Patch.Feedback).Assembly);
            var alertPath        = P42.Utils.EmbeddedResourceCache.LocalStorageFullPathForEmbeddedResource("Forms9Patch.Resources.Sounds.alert.ogg", typeof(Forms9Patch.Feedback).Assembly);
            var errorPath        = P42.Utils.EmbeddedResourceCache.LocalStorageFullPathForEmbeddedResource("Forms9Patch.Resources.Sounds.error.ogg", typeof(Forms9Patch.Feedback).Assembly);
            var messagePath      = P42.Utils.EmbeddedResourceCache.LocalStorageFullPathForEmbeddedResource("Forms9Patch.Resources.Sounds.message.ogg", typeof(Forms9Patch.Feedback).Assembly);
            var notificationPath = P42.Utils.EmbeddedResourceCache.LocalStorageFullPathForEmbeddedResource("Forms9Patch.Resources.Sounds.notification.ogg", typeof(Forms9Patch.Feedback).Assembly);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
            {
                var audioAttributes = new AudioAttributes.Builder()
                                      .SetUsage(AudioUsageKind.NotificationEvent)
                                      .SetContentType(AudioContentType.Sonification)
                                      .Build();
                _soundPool = new SoundPool.Builder()
                             .SetMaxStreams(5)
                             .SetAudioAttributes(audioAttributes)
                             .Build();
            }
            else
            {
                _soundPool = new SoundPool(5, Stream.Alarm, 0);
            }

            alarmId        = _soundPool.Load(alarmPath, 1);
            alertId        = _soundPool.Load(alertPath, 1);
            errorId        = _soundPool.Load(errorPath, 1);
            messageId      = _soundPool.Load(messagePath, 1);
            notificationId = _soundPool.Load(notificationPath, 1);
        }
        //public void Cancel(int id)
        //{
        //    var notificationManager = NotificationManagerCompat.From(_context);
        //    notificationManager.CancelAll();
        //    notificationManager.Cancel(id);
        //}
        public void LocalNotification(string title, string body, DateTime time)
        {
            try
            {
                //long repeateDay = 1000 * 60 * 60 * 24;
                long repeateForMinute  = 60000; // In milliseconds
                long totalMilliSeconds = (long)(time.ToUniversalTime() - _jan1st1970).TotalMilliseconds;
                if (totalMilliSeconds < JavaSystem.CurrentTimeMillis())
                {
                    totalMilliSeconds = totalMilliSeconds + repeateForMinute;
                }
                var intent = new Intent(_context, typeof(MainActivity));
                intent.AddFlags(ActivityFlags.ClearTop);
                intent.PutExtra(title, body);
                var pendingIntent = PendingIntent.GetActivity(_context, 0, intent, PendingIntentFlags.OneShot);

                // Creating an Audio Attribute
                var alarmAttributes = new AudioAttributes.Builder()
                                      .SetContentType(AudioContentType.Sonification)
                                      .SetUsage(AudioUsageKind.Notification).Build();

                _builder = new NotificationCompat.Builder(_context);
                _builder.SetSmallIcon(Resource.Drawable.app_logo);
                _builder.SetContentTitle(title)
                .SetAutoCancel(true)
                .SetContentTitle(title)
                .SetContentText(body)
                .SetChannelId(NOTIFICATION_CHANNEL_ID)
                .SetPriority((int)NotificationPriority.High)
                .SetVibrate(new long[0])
                .SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate)
                .SetVisibility((int)NotificationVisibility.Public)
                .SetSmallIcon(Resource.Drawable.theWitcher);

                NotificationManager notificationManager = _context.GetSystemService(Context.NotificationService) as NotificationManager;

                if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.O)
                {
                    NotificationImportance importance = global::Android.App.NotificationImportance.High;

                    NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, title, importance);
                    notificationChannel.EnableLights(true);
                    notificationChannel.EnableVibration(true);
                    notificationChannel.SetShowBadge(true);
                    notificationChannel.Importance = NotificationImportance.High;
                    notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });

                    if (notificationManager != null)
                    {
                        _builder.SetChannelId(NOTIFICATION_CHANNEL_ID);
                        notificationManager.CreateNotificationChannel(notificationChannel);
                    }
                }

                notificationManager.Notify(0, _builder.Build());
            }
            catch (Java.Lang.Exception ex)
            {
            }
        }
Beispiel #9
0
        public void CreateNotification(String title, String message)
        {
            try
            {
                var intent = new Intent(global::Android.App.Application.Context, typeof(MainActivity));
                intent.AddFlags(ActivityFlags.ClearTop);
                intent.PutExtra("title", message);
                var pendingIntent = PendingIntent.GetActivity(global::Android.App.Application.Context, 0, intent, PendingIntentFlags.OneShot);

                var sound = global::Android.Net.Uri.Parse(ContentResolver.SchemeAndroidResource + "://" + global::Android.App.Application.Context.PackageName + "/" + Resource.Raw.alert);
                // Creating an Audio Attribute
                var alarmAttributes = new AudioAttributes.Builder()
                                      .SetContentType(AudioContentType.Sonification)
                                      .SetUsage(AudioUsageKind.Notification).Build();

                mBuilder = new NotificationCompat.Builder(global::Android.App.Application.Context);
                mBuilder.SetSmallIcon(Resource.Drawable.abc);
                mBuilder.SetContentTitle(title)
                .SetSound(sound)
                .SetAutoCancel(true)
                .SetContentTitle(title)
                .SetContentText(message)
                .SetChannelId(NOTIFICATION_CHANNEL_ID)
                .SetPriority((int)NotificationPriority.High)
                .SetVibrate(new long[0])
                .SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate)
                .SetVisibility((int)NotificationVisibility.Public)
                .SetSmallIcon(Resource.Drawable.abc)
                .SetContentIntent(pendingIntent);



                NotificationManager notificationManager = global::Android.App.Application.Context.GetSystemService(Context.NotificationService) as NotificationManager;

                if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.O)
                {
                    NotificationImportance importance = global::Android.App.NotificationImportance.High;

                    NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, title, importance);
                    notificationChannel.EnableLights(true);
                    notificationChannel.EnableVibration(true);
                    notificationChannel.SetSound(sound, alarmAttributes);
                    notificationChannel.SetShowBadge(true);
                    notificationChannel.Importance = NotificationImportance.High;
                    notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });

                    if (notificationManager != null)
                    {
                        mBuilder.SetChannelId(NOTIFICATION_CHANNEL_ID);
                        notificationManager.CreateNotificationChannel(notificationChannel);
                    }
                }

                notificationManager.Notify(0, mBuilder.Build());
            }
            catch (Exception ex)
            {
                //
            }
        }
        void CreateNotificationChannel(Context context)
        {
            if (notificationManager == null)
            {
                if (Build.VERSION.SdkInt < BuildVersionCodes.O)
                {
                    return;
                }

                var name        = "Contento";
                var description = "Contento";
                var channel     = new NotificationChannel(CHANNEL_ID, name, NotificationImportance.Default)
                {
                    Description = description
                };
                var alarmAttributes = new AudioAttributes.Builder()
                                      .SetContentType(AudioContentType.Sonification)
                                      .SetUsage(AudioUsageKind.Notification).Build();
                Android.Net.Uri alarmUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
                channel.EnableLights(true);
                channel.EnableVibration(true);
                channel.Importance = NotificationImportance.High;
                channel.SetSound(alarmUri, alarmAttributes);

                notificationManager = (NotificationManager)context.GetSystemService("notification");
                notificationManager.CreateNotificationChannel(channel);
            }
        }
Beispiel #11
0
    public void start()
    {
        if (running)
        {
            Logging.warn("Audio player is already running.");
            return;
        }

        running = true;

        AudioAttributes aa = new AudioAttributes.Builder()
                             .SetContentType(AudioContentType.Speech)
                             .SetLegacyStreamType(Stream.VoiceCall)
                             .SetFlags(AudioFlags.LowLatency)
                             .SetUsage(AudioUsageKind.VoiceCommunication)
                             .Build();
        AudioFormat af = new AudioFormat.Builder()
                         .SetSampleRate(44100)
                         .SetChannelMask(ChannelOut.Mono)
                         .SetEncoding(Encoding.Pcm16bit)
                         .Build();

        audioPlayer = new AudioTrack(aa, af, AudioTrack.GetMinBufferSize(44100, ChannelOut.Mono, Encoding.Pcm16bit) * 100, AudioTrackMode.Stream, 0);

        audioPlayer.SetVolume(0.8f);

        audioPlayer.Play();
    }
Beispiel #12
0
        public DroidAudioManager()
        {
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
            {
                // Do things the Lollipop way
                var attributes = new AudioAttributes.Builder()
                                 .SetUsage(AudioUsageKind.Game)
                                 .SetContentType(AudioContentType.Music)
                                 .Build();

                _soundPool = new SoundPool.Builder()
                             .SetAudioAttributes(attributes)
                             .SetMaxStreams(10)
                             .Build();
            }
            else
            {
                // Do things the pre-Lollipop way
                _soundPool = new SoundPool(10, Android.Media.Stream.Music, 0);
            }

            //6, Stream.Music, 0


            // Initialize
            ActivateAudioSession();
        }
        void SendNotification(string messageBody, IDictionary <string, string> data)
        {
            var intent = new Intent(this, typeof(MainActivity));

            intent.AddFlags(ActivityFlags.ClearTop);
            foreach (var key in data.Keys)
            {
                intent.PutExtra(key, data[key]);
            }
            // Creating an Audio Attribute
            var alarmAttributes = new AudioAttributes.Builder()
                                  .SetContentType(AudioContentType.Sonification)
                                  .SetUsage(AudioUsageKind.Notification).Build();

            // Create the uri for the alarm file
            Android.Net.Uri alarmUri = Android.Net.Uri.Parse($"{ ContentResolver.SchemeAndroidResource}://{Application.Context.PackageName}/{Resource.Raw.soundfile}");

            var pendingIntent = PendingIntent.GetActivity(this, MainActivity.NOTIFICATION_ID, intent, PendingIntentFlags.OneShot);

            var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
                                      .SetSmallIcon(Resource.Drawable.watermelon)
                                      //.SetSound(alarmUri)
                                      .SetContentTitle("Self Tracker")
                                      .SetContentText(messageBody)
                                      .SetAutoCancel(true)
                                      .SetContentIntent(pendingIntent);

            var notificationManager = NotificationManagerCompat.From(this);

            notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());
        }
Beispiel #14
0
 private void PreviewAlarmAudioButton_Click(object sender, EventArgs e)
 {
     if (streamerData.NotifySoundPath == null)
     {
         Toast.MakeText(ApplicationContext, Resource.String.no_sound_on_play_notify_sound, ToastLength.Short).Show();
         return;
     }
     try
     {
         if (previewPlayer.IsPlaying)
         {
             previewPlayer.Stop();
         }
         else
         {
             previewPlayer.Reset();
             var builder = new AudioAttributes.Builder();
             builder.SetContentType(AudioContentType.Music);
             builder.SetUsage(AudioUsageKind.Alarm);
             previewPlayer.SetAudioAttributes(builder.Build());
             previewPlayer.SetDataSource(streamerData.NotifySoundPath); //SetDataSource(ApplicationContext, Uri.Parse(streamerData.NotifySoundPath));
             previewPlayer.Prepare();
             previewPlayer.Start();
         }
     }
     catch
     {
         Toast.MakeText(ApplicationContext, Resource.String.exception_on_play_notify_sound, ToastLength.Short).Show();
     }
 }
Beispiel #15
0
    private void initPlayer()
    {
        Encoding encoding = Encoding.Pcm16bit;

        bufferSize = AudioTrack.GetMinBufferSize(sampleRate, ChannelOut.Mono, encoding);
        Logging.info("Min. buffer size " + bufferSize);
        int new_buffer_size = CodecTools.getPcmFrameByteSize(sampleRate, bitRate, channels) * 100;

        if (bufferSize < new_buffer_size)
        {
            bufferSize = (int)(Math.Ceiling((decimal)new_buffer_size / bufferSize) * bufferSize);
        }
        Logging.info("Final buffer size " + bufferSize);

        // Prepare player
        AudioAttributes aa = new AudioAttributes.Builder()
                             .SetContentType(AudioContentType.Speech)
                             .SetFlags(AudioFlags.LowLatency)
                             .SetUsage(AudioUsageKind.VoiceCommunication)
                             .Build();

        AudioFormat af = new AudioFormat.Builder()
                         .SetSampleRate(sampleRate)
                         .SetChannelMask(ChannelOut.Mono)
                         .SetEncoding(encoding)
                         .Build();

        audioPlayer = new AudioTrack(aa, af, bufferSize, AudioTrackMode.Stream, 0);

        MainActivity.Instance.VolumeControlStream = Stream.VoiceCall;

        audioPlayer.Play();
    }
        private static void CreateNotificationChannel(string mChannel, string mTitle, string mContent)
        {
            string description = mContent;

            long[]          vibrationPattern = { 100, 200, 300, 400, 500, 400, 300, 200, 400 };
            Uri             sound            = Uri.Parse(ContentResolver.SchemeAndroidResource + "://" + Application.Context.PackageName + "/" + Resource.Raw.alarm); //Here is FILE_NAME is the name of file that you want to play
            AudioAttributes attributes       = new AudioAttributes.Builder()
                                               .SetUsage(AudioUsageKind.Alarm)
                                               .Build();

            var channel =
                new NotificationChannel(mChannel, mTitle, NotificationImportance.Default)
            {
                Description = description
            };

            channel.EnableVibration(true);
            channel.SetSound(sound, attributes);
            channel.SetVibrationPattern(vibrationPattern);
            var notificationManager =
                (NotificationManager)Application.Context.GetSystemService(
                    Context.NotificationService);

            notificationManager.CreateNotificationChannel(channel);
        }
        public void NotifyVersion26(Context context, Android.Content.Res.Resources res, Android.App.NotificationManager manager)
        {
            string channelName = "Secondary Channel";
            var    importance  = NotificationImportance.High;
            var    channel     = new NotificationChannel(PRIMARY_CHANNEL, channelName, importance);

            var path           = Android.Net.Uri.Parse("android.resource://com.ufinix.uberdriver/" + Resource.Raw.alert);
            var audioattribute = new AudioAttributes.Builder()
                                 .SetContentType(AudioContentType.Sonification)
                                 .SetUsage(AudioUsageKind.Notification).Build();

            channel.EnableLights(true);
            channel.EnableLights(true);
            channel.SetSound(path, audioattribute);
            channel.LockscreenVisibility = NotificationVisibility.Public;

            manager.CreateNotificationChannel(channel);

            Intent intent = new Intent(context, typeof(MainActivity));

            intent.AddFlags(ActivityFlags.SingleTop);
            PendingIntent pendingIntent = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.CancelCurrent);

            Notification.Builder builder = new Notification.Builder(context)
                                           .SetContentTitle("Uber Driver")
                                           .SetSmallIcon(Resource.Drawable.ic_location)
                                           .SetLargeIcon(BitmapFactory.DecodeResource(res, Resource.Drawable.iconimage))
                                           .SetContentText("You have a new trip request")
                                           .SetChannelId(PRIMARY_CHANNEL)
                                           .SetAutoCancel(true)
                                           .SetContentIntent(pendingIntent);

            manager.Notify(NOTIFY_ID, builder.Build());
        }
Beispiel #18
0
        private void SetAudioFocus(bool focused)
        {
            try
            {
                if (AudioManager == null)
                {
                    AudioManager = (AudioManager)Application.Context.GetSystemService(Context.AudioService);
                }

                if (focused)
                {
                    PreviousAudioMode      = AudioManager.Mode;
                    PreviousSpeakerphoneOn = AudioManager.SpeakerphoneOn;

                    if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                    {
                        var playbackAttributes = new AudioAttributes.Builder()
                                                 .SetUsage(AudioUsageKind.VoiceCommunication)
                                                 .SetContentType(AudioContentType.Speech)
                                                 .Build();

                        var focusRequest = new AudioFocusRequestClass.Builder(AudioFocus.Gain)
                                           .SetAudioAttributes(playbackAttributes)
                                           .SetAcceptsDelayedFocusGain(true)
                                           .SetOnAudioFocusChangeListener(this)
                                           .Build();

                        AudioManager.RequestAudioFocus(focusRequest);
                    }
                    else
                    {
#pragma warning disable 618
                        AudioManager.RequestAudioFocus(this, Stream.VoiceCall, AudioFocus.GainTransient);
#pragma warning restore 618
                    }

                    //Start by setting MODE_IN_COMMUNICATION as default audio mode. It is
                    //required to be in this mode when playout and/or recording starts for
                    //best possible VoIP performance. Some devices have difficulties with speaker mode
                    //if this is not set.
                    AudioManager.SpeakerphoneOn = TypeCall != TypeCall.Audio;

                    //AudioManager.SpeakerphoneOn = false;
                    AudioManager.Mode = Mode.InCommunication;
                }
                else
                {
                    AudioManager.Mode           = PreviousAudioMode;
                    AudioManager.SpeakerphoneOn = PreviousSpeakerphoneOn;
#pragma warning disable 618
                    AudioManager.AbandonAudioFocus(null);
#pragma warning restore 618
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #19
0
        private void SendNotification(string title, string body)
        {
            // Set custom push notification sound.
            Android.Net.Uri alarmUri        = Android.Net.Uri.Parse($"{ContentResolver.SchemeAndroidResource}://{this.Application.ApplicationContext.PackageName}/{Resource.Raw.notificationsound}");
            var             alarmAttributes = new AudioAttributes.Builder()
                                              .SetContentType(AudioContentType.Sonification)
                                              .SetUsage(AudioUsageKind.Notification).Build();
            //custom sounds end here

            var           nIntent       = new Intent(this, typeof(Login));
            PendingIntent pendingIntent = PendingIntent.GetActivity(Application.Context, 0, nIntent, PendingIntentFlags.OneShot);

            try
            {
                if (userId != 0 && issueId != 0)
                {
                    var intent = new Intent(Application.Context, typeof(MainActivity));
                    intent.AddFlags(ActivityFlags.ClearTop);
                    intent.PutExtra("userid", JsonConvert.SerializeObject(userId));
                    intent.PutExtra("issueid", JsonConvert.SerializeObject(issueId));
                    pendingIntent = PendingIntent.GetActivity(Application.Context, 0, intent, PendingIntentFlags.OneShot);
                }



                NotificationManager notificationmanager = (NotificationManager)GetSystemService(Context.NotificationService);
                if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
                {
                    NotificationChannel notificationchannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification Channel", Android.App.NotificationImportance.Max);
                    notificationchannel.Description = "ProblemUpdate Channel";
                    notificationchannel.EnableLights(true);
                    notificationchannel.LightColor = Android.Graphics.Color.Blue;
                    notificationchannel.SetSound(alarmUri, alarmAttributes);
                    notificationmanager.CreateNotificationChannel(notificationchannel);
                }
                NotificationCompat.Builder notificationbuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

                Android.Graphics.Bitmap bitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.appiconfinal);

                Android.Net.Uri alar_mUri = Android.Net.Uri.Parse($"{ContentResolver.SchemeAndroidResource}://{this.Application.ApplicationContext.PackageName}/{Resource.Raw.notificationsound}");
                notificationbuilder.SetAutoCancel(true)
                .SetWhen(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
                .SetContentTitle(title)
                .SetContentText(body)
                .SetSmallIcon(Resource.Drawable.r_myicon)
                .SetLargeIcon(bitmap)
                .SetSound(alar_mUri)
                .SetContentInfo("info")
                .SetContentIntent(pendingIntent);

                notificationmanager.Notify(new Random().Next(), notificationbuilder.Build());
            }
            catch (Exception)
            {
            }
        }
        private void SendNotification(ChatMessage message)
        {
            var intent = new Intent(this, typeof(MainActivity));

            intent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

            var defaultSoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);

            notificationBuilder = new NotificationCompat.Builder(this)
                                  .SetSmallIcon(Resource.Drawable.icon) // Display this icon
                                  .SetContentTitle(message.UserName)    // Set its title
                                  .SetContentText(message.Text)         // The message to display.
                                  .SetAutoCancel(true)                  // Dismiss from the notif. area when clicked
                                  .SetSound(defaultSoundUri)            // Sound of message
                                  .SetContentIntent(pendingIntent)
                                  .SetChannelId("10023")
                                  .SetPriority(1)
                                  .SetVisibility((int)NotificationVisibility.Public)
                                  .SetVibrate(new long[0]);

            if (App.IsActive)
            {
                var alarmAttributes = new AudioAttributes.Builder().SetContentType(AudioContentType.Sonification).SetUsage(AudioUsageKind.Notification).Build();
                NotificationManager notificationManager = mContext.GetSystemService(Context.NotificationService) as NotificationManager;
                if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.O)
                {
                    NotificationImportance importance           = global::Android.App.NotificationImportance.High;
                    NotificationChannel    notificationChannels = new NotificationChannel("10023", message.UserName, importance);
                    notificationChannels.EnableLights(true);
                    notificationChannels.EnableVibration(true);
                    notificationChannels.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification), alarmAttributes);
                    notificationChannels.Importance = NotificationImportance.Max;
                    notificationChannels.SetVibrationPattern(new long[] { 100, 100, 100, 300, 300, 100, 100, 100 });
                    if (notificationManager != null)
                    {
                        notificationBuilder.SetChannelId("10023");
                        notificationManager.CreateNotificationChannel(notificationChannels);
                    }
                    notificationManager.Notify(0, notificationBuilder.Build());
                }
                else
                {
                    var notificationManager1 = NotificationManager.FromContext(this);
                    notificationManager1.Notify(idPush++, notificationBuilder.Build());
                }
                //remove after debug
                var chatService = ViewModelLocator.Instance.Resolve(typeof(ChatService)) as IChatService;
                chatService.OnMessageReceived(message);
            }
            else
            {
                var chatService = ViewModelLocator.Instance.Resolve(typeof(ChatService)) as IChatService;
                chatService.OnMessageReceived(message);
            }
        }
        public void CreateNotification(String title, String message)
        {
            try
            {
                var sound = global::Android.Net.Uri.Parse(ContentResolver.SchemeAndroidResource + "://" + mContext.PackageName + "/" + Resource.Raw.notification);
                // Creating an Audio Attribute
                var alarmAttributes = new AudioAttributes.Builder()
                                      .SetContentType(AudioContentType.Sonification)
                                      .SetUsage(AudioUsageKind.Notification).Build();


                mBuilder = new NotificationCompat.Builder(mContext);
                mBuilder.SetSmallIcon(Resource.Drawable.notification_bg);//revisar
                mBuilder.SetContentTitle(title)
                .SetSound(sound)
                .SetAutoCancel(true)
                .SetContentTitle(title)
                .SetContentText(message)
                .SetChannelId(NOTIFICATION_CHANNEL_ID)
                .SetPriority((int)NotificationPriority.High)
                .SetVibrate(new long[0])
                .SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate)
                .SetVisibility((int)NotificationVisibility.Public)
                .SetSmallIcon(Resource.Drawable.notification_bg);


                NotificationManager notificationManager = mContext.GetSystemService(Context.NotificationService) as NotificationManager;

                if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.O)
                {
                    NotificationImportance importance = global::Android.App.NotificationImportance.High;

                    NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, title, importance);
                    notificationChannel.EnableLights(true);
                    notificationChannel.EnableVibration(true);
                    notificationChannel.SetSound(sound, alarmAttributes);
                    notificationChannel.SetShowBadge(true);
                    notificationChannel.Importance = NotificationImportance.High;
                    notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });

                    if (notificationManager != null)
                    {
                        mBuilder.SetChannelId(NOTIFICATION_CHANNEL_ID);
                        notificationManager.CreateNotificationChannel(notificationChannel);
                    }
                }

                notificationManager.Notify(0, mBuilder.Build());
            }
            catch (Exception ex)
            {
                Log.Debug("Error: ", ex.Message);
            }
        }
        //public void Write(byte[] bytes)
        //{
        //    /*
        //    foreach(System.IO.Stream temp in streamList)
        //    {
        //        try
        //        {
        //            temp.Write(bytes);
        //        }
        //        catch (System.IO.IOException ex)
        //        {
        //            System.Diagnostics.Debug.WriteLine("Error occurred when sending data", ex);
        //        }
        //    }
        //    *
        //    */

        //    try
        //    {
        //        mmOutStream.Write(bytes);
        //    }
        //    catch (System.IO.IOException ex)
        //    {
        //        System.Diagnostics.Debug.WriteLine("Error occurred when sending data", ex);
        //    }

        //}

        public void Write(System.IO.Stream stream)
        {
            /*
             * foreach(System.IO.Stream temp in streamList)
             * {
             *  try
             *  {
             *      temp.Write(bytes);
             *  }
             *  catch (System.IO.IOException ex)
             *  {
             *      System.Diagnostics.Debug.WriteLine("Error occurred when sending data", ex);
             *  }
             * }
             *
             */
            AudioTrack _output;

            int buffsize = AudioTrack.GetMinBufferSize(44100, ChannelOut.Stereo, Android.Media.Encoding.Pcm16bit);
            //_output = new AudioTrack(Android.Media.Stream.Music, 44100, ChannelOut.Stereo, Android.Media.Encoding.Pcm16bit,
            //buffsize, AudioTrackMode.Stream);
            var AABuilder = new AudioAttributes.Builder();

            AABuilder.SetContentType(AudioContentType.Music);
            AABuilder.SetUsage(AudioUsageKind.Media);

            var AfBuilder = new AudioFormat.Builder();

            AfBuilder.SetSampleRate(44100);
            AfBuilder.SetEncoding(Android.Media.Encoding.Pcm16bit);
            AfBuilder.SetChannelMask(ChannelOut.Stereo);


            _output = new AudioTrack(AABuilder.Build(), AfBuilder.Build(), buffsize, AudioTrackMode.Stream, AudioManager.AudioSessionIdGenerate);
            _output.Play();
            try
            {
                byte[] buffer        = new byte[1000];
                int    bytesReturned = 1;

                while (bytesReturned > 0)
                {
                    bytesReturned = stream.Read(buffer, 0, buffer.Length);
                    mmOutStream.Write(buffer);
                    _output.Write(buffer, 0, buffer.Length);
                    //DependencyService.Get<BluetoothManager>().Write(buffer);
                }
                stream.Close();
            }
            catch (System.IO.IOException ex)
            {
                System.Diagnostics.Debug.WriteLine("Error occurred when sending data", ex);
            }
        }
Beispiel #23
0
        public async Task PlayStream(string url)
        {
            await SetSource(url);

            if (OS.IsAtLeast(Android.OS.BuildVersionCodes.O))
            {
                var attributes = new AudioAttributes.Builder().SetLegacyStreamType(Stream.Music).Build();
                Player.SetAudioAttributes(attributes);
            }

            Player.Start();
        }
Beispiel #24
0
    public void start(string codec)
    {
        if (running)
        {
            Logging.warn("Audio recorder is already running.");
            return;
        }
        running = true;

        AudioManager am = (AudioManager)MainActivity.Instance.GetSystemService(Context.AudioService);

        if (Build.VERSION.SdkInt < BuildVersionCodes.O)
        {
            focusListener = new AudioFocusListener();
#pragma warning disable CS0618 // Type or member is obsolete
            am.RequestAudioFocus(focusListener, Stream.VoiceCall, AudioFocus.GainTransient);
#pragma warning restore CS0618 // Type or member is obsolete
        }
        else
        {
            AudioAttributes aa = new AudioAttributes.Builder()
                                 .SetContentType(AudioContentType.Speech)
                                 .SetFlags(AudioFlags.LowLatency)
                                 .SetUsage(AudioUsageKind.VoiceCommunication)
                                 .Build();

            focusListener = new AudioFocusListener();

            focusRequest = new AudioFocusRequestClass.Builder(AudioFocus.GainTransient)
                           .SetAudioAttributes(aa)
                           .SetFocusGain(AudioFocus.GainTransient)
                           .SetOnAudioFocusChangeListener(focusListener)
                           .Build();
            am.RequestAudioFocus(focusRequest);
        }

        lock (outputBuffers)
        {
            outputBuffers.Clear();
        }

        bufferSize = AudioTrack.GetMinBufferSize(sampleRate, ChannelOut.Mono, Encoding.Pcm16bit);

        initEncoder(codec);
        initRecorder();

        recordThread = new Thread(recordLoop);
        recordThread.Start();

        senderThread = new Thread(senderLoop);
        senderThread.Start();
    }
        public void Play()
        {
            MediaPlayer = new MediaPlayer();
            var attributesBuilder = new AudioAttributes.Builder();

            attributesBuilder.SetLegacyStreamType(Stream.Music);
            attributesBuilder.SetContentType(AudioContentType.Music);
            MediaPlayer.SetAudioAttributes(attributesBuilder.Build()); MediaPlayer.SetOnErrorListener(this);
            MediaPlayer.SetOnInfoListener(this);
            MediaPlayer.SetOnPreparedListener(this);
            MediaPlayer.SetDataSource("http://stream.intronic.nl/rgrfm_oldiesradio");
            MediaPlayer.PrepareAsync();
        }
Beispiel #26
0
        public SimplePhraseMessenger(TextToSpeech speechEngine, string phrase, int numRepeats)
        {
            this.speechEngine = speechEngine;
            this.phrase       = phrase;
            this.numRepeats   = numRepeats;
            AudioAttributes.Builder b = new AudioAttributes.Builder();
            b.SetFlags(AudioFlags.LowLatency);
            b.SetUsage(AudioUsageKind.Alarm);
            b.SetContentType(AudioContentType.Speech);

            AudioAttributes audioAttributes = b.Build();

            speechEngine.SetAudioAttributes(audioAttributes);
        }
Beispiel #27
0
        public DroidAudioManager()
        {
            var attributes = new AudioAttributes.Builder()
                             .SetUsage(AudioUsageKind.Game)
                             .SetContentType(AudioContentType.Music)
                             .Build();

            _soundPool = new SoundPool.Builder()
                         .SetAudioAttributes(attributes)
                         .SetMaxStreams(10)
                         .Build();

            // Initialize
            ActivateAudioSession();
        }
Beispiel #28
0
        private void createAlarmMedicationChannel()
        {
            Uri sound = Uri.Parse(ContentResolver.SchemeAndroidResource + "://" + Application.Context.PackageName +
                                  "/" + Resource.Raw
                                  .alarm);                     //Here is FILE_NAME is the name of file that you want to play
            AudioAttributes attributes = new AudioAttributes.Builder().SetUsage(AudioUsageKind.Notification).Build();

            var channel = new NotificationChannel(App.AlarmMedicationChannelId,
                                                  "Alarm medication", NotificationImportance.High);

            channel.SetSound(sound, attributes);

            ((NotificationManager)GetSystemService(NotificationService)).CreateNotificationChannel(channel);
            Log.Error("MainActivity App CreateChannel", "Test alarm medication channel created");
        }
Beispiel #29
0
        private async void PlayRingtone()
        {
            if (!ServiceProvider.SettingsProvider.IsDndModeEnabled)
            {
                try
                {
                    var ringtone = RingtoneManager.GetActualDefaultRingtoneUri(this, RingtoneType.Ringtone);

                    _mediaPlayer = new MediaPlayer();

                    _mediaPlayer.SetDataSource(this, ringtone);

                    if (int.Parse(Build.VERSION.Sdk) >= 21)
                    {
                        var customAudioAttributes = new AudioAttributes.Builder()

                                                    .SetUsage(AudioUsageKind.NotificationRingtone)
                                                    .SetContentType(AudioContentType.Sonification)
                                                    .Build();

                        _mediaPlayer.SetAudioAttributes(customAudioAttributes);
                    }
                    else
                    {
#pragma warning disable CS0618 // Type or member is obsolete
                        _mediaPlayer.SetAudioStreamType(Stream.Ring);
#pragma warning restore CS0618 // Type or member is obsolete
                    }

                    _mediaPlayer.Looping = true;

                    _mediaPlayer.Prepare();
                    _mediaPlayer.Start();

                    await Task.Delay(30 * 1000).ContinueWith(_ =>
                    {
                        StopRingtone();
                        TurnFlashlightNotificationsOff();
                    });
                }
                catch (Exception ex)
                {
                    ServiceProvider.LoggingService.Log(ex, LogType.Error);
                }
            }
        }
Beispiel #30
0
        private NotificationChannel BuildChannel()
        {
            var channel = new NotificationChannel(Constants.CHANNEL_ID
                                                  , Constants.CHANNEL_NAME, NotificationImportance.High)
            {
                LockscreenVisibility = NotificationVisibility.Public,
            };

            channel.EnableVibration(true);

            var alarmAttributes = new AudioAttributes.Builder()
                                  .SetContentType(AudioContentType.Sonification)
                                  .SetUsage(AudioUsageKind.Notification).Build();

            channel.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification), alarmAttributes);
            return(channel);
        }