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

前端 未结 2 653
走了就别回头了
走了就别回头了 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();
    }
    
    0 讨论(0)
  • 2021-01-04 10:43

    You can either call mp.reset() and then set the stream type, data source, and then prepare. Alternately just use the default constructor and handle the initialization yourself.

    EDIT:

    Resources res = getResources();
    AssetFileDescriptor afd = res.openRawResourceFd(R.raw.alarm);
    
    mp.reset();
    mp.setAudioStreamType(AudioManager.STREAM_ALARM);
    mp.setLooping(true);
    mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    mp.prepare();
    mp.start();
    
    0 讨论(0)
提交回复
热议问题