Friday, 9 May 2014

Playing system notification sound with soundpool, converting uri to path

Here is short example, I think there is no need to explain. This works from 2.3+

 //take an uri and convert to path  
 Uri uriSound = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION;  
 String soundPath = getRealPathFromURI(uriSound);  
   
 //get natification system volume  
 AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);  
 final int currentVolume = audio.getStreamVolume(AudioManager.STREAM_NOTIFICATION);  
   
 //create pool, load system notification sound, when load - set volume and play  
 SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 0);  
 final int loadedNotification = soundPool.load(soundPath, 1);  
 soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {  
      @Override  
      public void onLoadComplete(SoundPool soundPool, int i, int i2) {  
           soundPool.setVolume(loadedNotification, currentVolume, currentVolume);  
           soundPool.play(loadedNotification, 1, 1, 1, 0, 1);  
      }  
 });  
   
 //somewhere created method...  
   
 private String getRealPathFromURI(Uri contentUri) {  
      String[] proj = { MediaStore.Images.Media.DATA };  
      CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);  
      Cursor cursor = loader.loadInBackground();  
      int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
      cursor.moveToFirst();  
      return cursor.getString(column_index);  
 }