Android MediaPlayer - how to play in the STREAM_ALARM?

前端 未结 5 860
南旧
南旧 2020-12-16 16:32

I\'ve tried settings the audio stream of the media player in my application using the following code but when I do this I hear no sound in the emulator. If I don\'t set the

相关标签:
5条回答
  • 2020-12-16 16:54

    The issue is you are using MediaPlayer.create() to create your MediaPlayer. Create function calls the prepare() function which finalize your media and does not allow you to change AudioStreamType.

    The solution is using setDataSource instead of create:

    MediaPlayer mp = new MediaPlayer();
    mp.setAudioStreamType(AudioManager.STREAM_ALARM);
    mp.setLooping(true);
    try {
       mp.setDataSource(getApplicationContext(), yourAudioUri);
       mp.prepare();
    } catch (IOException e) {
       e.printStackTrace();
    }
    mp.start();
    

    See this link for more information.

    0 讨论(0)
  • 2020-12-16 16:54

    Try the following:

    player.setAudioStreamType(AudioManager.STREAM_ALARM);
    player.prepare();
    player.start();
    

    And why are you calling "audioManager.getStreamVolume(AudioManager.STREAM_ALARM);"? The value isn't stored in a variable, so it is rather useless ;)

    I hope that helped

    0 讨论(0)
  • 2020-12-16 16:57

    The solution here was deprecated in API 22

    I opened my own thread to figure this out.

    Here is an updated working solution.

    mediaPlayerScan = new MediaPlayer();
    try {
      mediaPlayerScan.setDataSource(getContext(),
              Uri.parse(getString(R.string.res_path) + R.raw.scan_beep));
    
      if (Build.VERSION.SDK_INT >= 21) {
        mediaPlayerScan.setAudioAttributes(new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_ALARM)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build());
      } else {
        mediaPlayerScan.setAudioStreamType(AudioManager.STREAM_ALARM);
      }
      mediaPlayerScan.prepare();
    } catch (IOException e) {
      e.printStackTrace();
    }
    
    0 讨论(0)
  • 2020-12-16 17:03

    I don't know why this would happen, however the code below works. You should set the data source with setDataSource() instead of with create().

    This code works:

    MediaPlayer mp = new MediaPlayer();
    mp.setAudioStreamType(AudioManager.STREAM_ALARM);
    mp.setDataSource(this,Uri.parse("android.resource://PACKAGE_NAME/"+R.raw.soundfile));
    mp.prepare();
    mp.start();
    

    This code doesn't work:

    MediaPlayer mp = MediaPlayer.create(this, R.raw.soundfile);
    mp.setAudioStreamType(AudioManager.STREAM_ALARM);
    mp.prepare();
    mp.start();
    
    0 讨论(0)
  • 1. setAudioStreamType(int streamtype)

    Must call this method before prepare() ;

    2. MediaPlayer.create(Context context, int resid)

    On success, prepare() will already have been called and must not be called again.

    0 讨论(0)
提交回复
热议问题