Notification播放apk中自带raw音频

  |   0 评论   |   50 浏览

    • 本场景为自定义Notification的声音
    • 根本解决方式是修改notification的sound

      notification.sound =Uri sound;
      //或者
      NotificationCompat.Builder.setSound(Uri sound)
      
    • Uri的规范可以参考 http://www.ietf.org/rfc/rfc2396.txt 以下为示例

      Uri sound=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notificationsound );  
      //或者
      Uri sound=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/notificationsound"); 
      //或者
      Uri sound=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/"+R.raw.notificationsound); 
      //或者从铃声管理器获取 
      Uri sound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
      
    • 也可以将一个无声音的音频文件指定给notification使其静音,然后启用MediaPlayer播放铃声。播放代码如下:

      try {
        Context context = Application.getInstance();
        MediaPlayer mediaPlayer;
        if (rawId > 0) {
          if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
              mediaPlayer = MediaPlayer.create(context, rawId);
      	} else {
      	  int sessionId = ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).generateAudioSessionId();
      	  AudioAttributes audioAttributes = new AudioAttributes.Builder()
      			  .setUsage(AudioAttributes.USAGE_NOTIFICATION)
      			  .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
      			  .setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
      			  .build();
      	  mediaPlayer = MediaPlayer.create(context, rawId, audioAttributes, sessionId);
      	}
      } else {
          mediaPlayer = MediaPlayer.create(context, RingtoneManager.getActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION));
      }
       //使用MediaPlayer.create(context, R.raw.mingdao)这种方式创建的MediaPlayer已经prepare完成,且不能修改AudioStreamType
       //mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);  
       mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
          @Override
      	public void onCompletion(MediaPlayer mediaPlayer) {
              mediaPlayer.release();
      }
      });
      mediaPlayer.start();
      } catch (Exception e) {
      e.printStackTrace();
      }
      

    知识共享许可协议

    评论

    发表评论

    validate