如何在 Android 中静音 MediaPlayer

发布于 2024-10-10 08:56:22 字数 34 浏览 4 评论 0原文

如何在 Android 中静音 MediaPlayer

How to mute MediaPlayer in android

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

暮色兮凉城 2024-10-17 08:56:22

这段代码对我有用,

MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1);
mp.start();

适用于静音

mp.setVolume(0,0);

& 取消静音全音量

mp.setVolume(1,1);

This code worked for me,

MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1);
mp.start();

for Mute

mp.setVolume(0,0);

& Unmute or full volume

mp.setVolume(1,1);
熟人话多 2024-10-17 08:56:22
 AudioManager   mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);

    int current_volume =mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    //If you want to player is mute ,then set_volume variable is zero.Otherwise you may supply some value.
    int set_volume=0;
    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,set_volume, 0);
 AudioManager   mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);

    int current_volume =mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    //If you want to player is mute ,then set_volume variable is zero.Otherwise you may supply some value.
    int set_volume=0;
    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,set_volume, 0);
坠似风落 2024-10-17 08:56:22

您可能想要淡出/淡入声音,而不是立即将其设置为最大 (1.0f) 或零 (0.0f) 音量。

这有点棘手,因为您需要一个异步任务来保持应用程序响应:

mpMain 是我的 MediaPlayer 实例来播放循环背景音乐。
我也在OnPause()和OnResume()中关心它。

playBackgroundMusic 方法用于打开音乐,fadeOutBackgroundMusic 关闭音乐,但通过淡出音量 0.5 秒(10*50,请参阅 while 和 Thread.sleep)。

我的基本卷是 0.8f,您可能希望将其作为异步任务的参数或使用静态全局变量。

public void playBackgroundMusic( Boolean isOn ){
  if(isOn){
    // prevent conflics with async fade-out task
    if(mtask_fadeout_music!=null){
      mtask_fadeout_music.cancel(true);
      mtask_fadeout_music=null;
    }
    if(mpMain==null){
      mpMain = MediaPlayer.create(this, R.raw.zin___piano_2_140bpm_32158);
      mpMain.setLooping(true);
      mpMain.setVolume(0.8f,0.8f);
      mpMain.start();                         
    }
  }
  else{
    if(mtask_fadeout_music==null){
      fadeOutBackgroundMusic();
    }
  }
}

public void fadeOutBackgroundMusic(){
  mtask_fadeout_music = (FadeOutMusic)new FadeOutMusic( ).execute( );
}


//
//  background processing ... fade out music stream
//
public class FadeOutMusic extends AsyncTask<String,Integer,String> {

  @Override
  protected String doInBackground(String... args) {
    float level = 0.8f;
    int i = 1;

    while(i<50){
        i++;
        if(mpMain != null){
          level=level*0.9f;
          mpMain.setVolume(level, level);         
        }
        try {
          Thread.sleep(10);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
    }
    return "dummy";
  }

  @Override
  protected void onPostExecute( String dummy ) {
    if(mpMain != null){
      mpMain.setVolume(0,0);         
      mpMain.release();
      mpMain = null;  
    }
    if(mtask_fadeout_music!=null){
      mtask_fadeout_music = null;
    }
  }       

  @Override
  public void onCancelled() {
    if(mpMain != null){
      mpMain.setVolume(0,0);         
      mpMain.release();
      mpMain = null;  
    }
    if(mtask_fadeout_music!=null){
      mtask_fadeout_music = null;
    }
  }
}

You might want to fade out/in the sound instead of setting it immediately to full (1.0f) or zero (0.0f) volume.

It's a little bit tricky, because you need an async task to keep your app responsive:

mpMain is my MediaPlayer instance to play the looping background music.
I also care about it in OnPause() and OnResume().

Method playBackgroundMusic is used to turn the music on, fadeOutBackgroundMusic turns music off, but by fading out volume for 0.5 seconds (10*50, see while and Thread.sleep).

My base-volume is 0.8f, you might want to make that a parameter of the async task or use a static global variable.

public void playBackgroundMusic( Boolean isOn ){
  if(isOn){
    // prevent conflics with async fade-out task
    if(mtask_fadeout_music!=null){
      mtask_fadeout_music.cancel(true);
      mtask_fadeout_music=null;
    }
    if(mpMain==null){
      mpMain = MediaPlayer.create(this, R.raw.zin___piano_2_140bpm_32158);
      mpMain.setLooping(true);
      mpMain.setVolume(0.8f,0.8f);
      mpMain.start();                         
    }
  }
  else{
    if(mtask_fadeout_music==null){
      fadeOutBackgroundMusic();
    }
  }
}

public void fadeOutBackgroundMusic(){
  mtask_fadeout_music = (FadeOutMusic)new FadeOutMusic( ).execute( );
}


//
//  background processing ... fade out music stream
//
public class FadeOutMusic extends AsyncTask<String,Integer,String> {

  @Override
  protected String doInBackground(String... args) {
    float level = 0.8f;
    int i = 1;

    while(i<50){
        i++;
        if(mpMain != null){
          level=level*0.9f;
          mpMain.setVolume(level, level);         
        }
        try {
          Thread.sleep(10);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
    }
    return "dummy";
  }

  @Override
  protected void onPostExecute( String dummy ) {
    if(mpMain != null){
      mpMain.setVolume(0,0);         
      mpMain.release();
      mpMain = null;  
    }
    if(mtask_fadeout_music!=null){
      mtask_fadeout_music = null;
    }
  }       

  @Override
  public void onCancelled() {
    if(mpMain != null){
      mpMain.setVolume(0,0);         
      mpMain.release();
      mpMain = null;  
    }
    if(mtask_fadeout_music!=null){
      mtask_fadeout_music = null;
    }
  }
}
红墙和绿瓦 2024-10-17 08:56:22

AudioManger.setStreamMute 已弃用。
使用下面的替代代码。

AudioManager am = getSystemService(Context.AUDIO_SERVICE);
// Change the stream to your stream of choice. 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
       am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE, 0);
    } else {
       am.setStreamMute(AudioManager.STREAM_MUSIC, true);
    }

AudioManger.setStreamMute is deprecated.
use below alternative code.

AudioManager am = getSystemService(Context.AUDIO_SERVICE);
// Change the stream to your stream of choice. 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
       am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE, 0);
    } else {
       am.setStreamMute(AudioManager.STREAM_MUSIC, true);
    }
疾风者 2024-10-17 08:56:22

我们可以使用以下方法来用于静音/取消静音或检查音频播放器是否处于静音状态

/**
 * To Mute or Un-mute using Audio Manager
 */
private fun updateMuteState(mute: Boolean) {
    activity?.let {
        getAudioManager(it).adjustStreamVolume(
            AudioManager.STREAM_MUSIC,
            if (mute) -100 else 100,
            0
        )
    }
}

/**
 * Return true -> audio player is in mute state, false otherwise
 */
private fun isMute(): Boolean {
    activity?.let {
        getAudioManager(it).getStreamVolume(AudioManager.STREAM_MUSIC).let { volume ->
            return volume == 0
        }
    }
    return false
}

/**
 * To Get the Audio Manager
 */
private fun getAudioManager(context: Context) =
    context.getSystemService(Context.AUDIO_SERVICE) as AudioManager

We can use below methods to use for mute/unmute or to check whether the audio player is in mute state or not

/**
 * To Mute or Un-mute using Audio Manager
 */
private fun updateMuteState(mute: Boolean) {
    activity?.let {
        getAudioManager(it).adjustStreamVolume(
            AudioManager.STREAM_MUSIC,
            if (mute) -100 else 100,
            0
        )
    }
}

/**
 * Return true -> audio player is in mute state, false otherwise
 */
private fun isMute(): Boolean {
    activity?.let {
        getAudioManager(it).getStreamVolume(AudioManager.STREAM_MUSIC).let { volume ->
            return volume == 0
        }
    }
    return false
}

/**
 * To Get the Audio Manager
 */
private fun getAudioManager(context: Context) =
    context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
予囚 2024-10-17 08:56:22

试试这个...

   AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
manager.setStreamMute(AudioManager.STREAM_MUSIC, true);

它将静音 完整的媒体音量静音

Try this...

   AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
manager.setStreamMute(AudioManager.STREAM_MUSIC, true);

It will mute Complete media volume to mute

ㄟ。诗瑗 2024-10-17 08:56:22

试试这个

AudioManager am = getSystemService(Context.AUDIO_SERVICE);
// Request audio focus.
am.requestAudioFocus(listener, AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN);

http://developer.android.com/training/managing-audio /audio-focus.html

Try this

AudioManager am = getSystemService(Context.AUDIO_SERVICE);
// Request audio focus.
am.requestAudioFocus(listener, AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN);

http://developer.android.com/training/managing-audio/audio-focus.html

遗心遗梦遗幸福 2024-10-17 08:56:22

即使在静音模式下,对我来说取消静音也有用

 MediaPlayer mMediaPlayer = new MediaPlayer();
 mMediaPlayer.setDataSource(this, alarmUri);
 mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
 mMediaPlayer.setVolume(0.7f,0.7f);
 mMediaPlayer.prepare();
 mMediaPlayer.start();

What worked for me for un-mute even in silent mode

 MediaPlayer mMediaPlayer = new MediaPlayer();
 mMediaPlayer.setDataSource(this, alarmUri);
 mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
 mMediaPlayer.setVolume(0.7f,0.7f);
 mMediaPlayer.prepare();
 mMediaPlayer.start();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文