(Android MediaPlayer) How am I supposed to call setAudioStreamType() if MediaPlayer.create() implicitly calls prepare()?

前端 未结 2 652
走了就别回头了
走了就别回头了 2021-01-04 10:02

I am writing an Android alarm application that uses a Service in order to play the alarm tone. Currently, I am able to get the audio to play, but it plays in a form that can

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-04 10:20

    Accepted answer was throwing an IllegalStateException. This is working

    MediaPlayer mediaPlayer = new MediaPlayer();
    
    try {
      mediaPlayer.setDataSource(
              this,
              getCustomToneUri()
      );
    
      mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
    
      mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
          mp.start();
        }
      });
    
      mediaPlayer.prepareAsync();
    } catch (IOException e) {
      e.printStackTrace();
    }
    

提交回复
热议问题