Playing sound on the alarm channel on android

前端 未结 2 1396
余生分开走
余生分开走 2020-12-01 19:43

I have done a lot of googling but other\'s solutions are not working for me.

My goal is to play a sound on demand on the alarm channel.
(So the sound volume is a

2条回答
  •  情深已故
    2020-12-01 20:07

    The problem is that create() puts the MediaPlayer in a state where it won't accept the attributes (it calls prepare() for you). You need to use the more verbose mechanism of creating the player.

      final MediaPlayer mediaPlayer = new MediaPlayer();
      mediaPlayer.setDataSource(...);
    
      AudioAttributes attrs = new AudioAttributes.Builder().setUsage(usage).build();
      mediaPlayer.setAudioAttributes(attrs);
    
      new AsyncTask() {
        @Override
        protected Boolean doInBackground(Void... voids) {
          try {
            mediaPlayer.prepare();
            return true;
          } catch (IOException e) {
            e.printStackTrace();
          }
          return false;
        }
    
        @Override
        protected void onPostExecute(Boolean prepared) {
          if (prepared) {
              mediaPlayer.start();
          }
        }
      }.execute();
    

提交回复
热议问题