如何在 Android 中以编程方式增加和减少音量

Posted

技术标签:

【中文标题】如何在 Android 中以编程方式增加和减少音量【英文标题】:How to increase and decrease the volume programmatically in Android 【发布时间】:2017-04-16 23:33:10 【问题描述】:

我创建了一个音乐播放器应用,我想以编程方式调高/调低音量。我想实现两个Buttons 来增加/减少音量并设置为媒体播放器。

活动

control = (ImageView) findViewById(R.id.control);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudiostreamType(AudioManager.STREAM_MUSIC);
control.setOnClickListener(pausePlay);
control.setBackgroundResource(R.drawable.pause);
control id is my play and pause button :

        // TODO Auto-generated method stub
        // TODO Auto-generated method stub

        if (playPause) 
            control.setBackgroundResource(R.drawable.play);
            if (mediaPlayer.isPlaying())
                mediaPlayer.pause();
            media.stop();
            intialStage = false;
            playPause = false;

         else 
            control.setBackgroundResource(R.drawable.pause);
            if (intialStage) 
                new Player()
                        .execute("http://streaming.shoutcast.com/MUKILFMRADIO");
             else 
                if (!mediaPlayer.isPlaying())
                    mediaPlayer.start();
            
            playPause = true;
        

布局

<LinearLayout
    android:layout_
    android:layout_
    android:orientation="horizontal"
    android:gravity="center">
    <ImageView
        android:layout_
        android:layout_
        android:id="@+id/control1"
        android:layout_margin="10dp"
        android:layout_gravity="center"
        android:background="@drawable/decrement"
        android:layout_above="@+id/latestAddedSongs"
        android:layout_alignEnd="@+id/musicArtistName" />
    <ImageView
        android:layout_
        android:layout_
        android:id="@+id/control"
        android:layout_margin="10dp"
        android:layout_gravity="center"
        android:background="@drawable/play"
        android:layout_above="@+id/latestAddedSongs"
        android:layout_alignEnd="@+id/musicArtistName" />
    <ImageView
        android:layout_
        android:layout_
        android:id="@+id/control2"
        android:layout_margin="10dp"
        android:layout_gravity="center"
        android:background="@drawable/increment"
        android:layout_above="@+id/latestAddedSongs"
        android:layout_alignEnd="@+id/musicArtistName" />
</LinearLayout>

【问题讨论】:

您想管理媒体播放器的音量吗?使用mAudioManager.setStreamVolume(3, paramAnonymousInt, 0) 但是如何将功能设置为我的上下按钮 向我展示完整的 xml 和完整的 java .. 即编辑您的问题 【参考方案1】:

为音频管理器创建一个对象

AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);


Button upButton = (Button) findViewById(R.id.upButton);
        upButton.setOnClickListener(new OnClickListener() 
            
            @Override
            public void onClick(View v) 

                //To increase media player volume               
                audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
            
        );
        
        Button downButton = (Button) findViewById(R.id.downButton);
        downButton.setOnClickListener(new OnClickListener() 
            
            @Override
            public void onClick(View v) 
                
                //To decrease media player volume
                audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);             
            
        );

上面的例子使用了Button标签

音量上下 代码

@Override
    public boolean dispatchKeyEvent(KeyEvent event) 
        int action = event.getAction();
        int keyCode = event.getKeyCode();
        switch (keyCode) 
            case KeyEvent.KEYCODE_VOLUME_UP:
                if (action == KeyEvent.ACTION_DOWN) 
                    audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
                
                return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if (action == KeyEvent.ACTION_DOWN) 
                    audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
                
                return true;
            default:
                return super.dispatchKeyEvent(event);
        
    

【讨论】:

【参考方案2】:

试试下面的代码

audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

seekbar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));

seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() 
  @Override
  public void onProgressChanged(SeekBar seekBar, int newVolume, boolean b) 
    textview.setText("Media Volume : " + newVolume);
    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, 0);
  

  @Override
  public void onStartTrackingTouch(SeekBar seekBar) 

  @Override
  public void onStopTrackingTouch(SeekBar seekBar) 
);

【讨论】:

感谢您的回答!。它工作完美。简单易行的答案。【参考方案3】:

下面的代码效果很好

Android 中有几个可用的流可以用来管理音频

 /** The audio stream for phone calls */
    public static final int STREAM_VOICE_CALL = AudioSystem.STREAM_VOICE_CALL;
    /** The audio stream for system sounds */
    public static final int STREAM_SYSTEM = AudioSystem.STREAM_SYSTEM;
    /** The audio stream for the phone ring */
    public static final int STREAM_RING = AudioSystem.STREAM_RING;
    /** The audio stream for music playback */
    public static final int STREAM_MUSIC = AudioSystem.STREAM_MUSIC;
    /** The audio stream for alarms */
    public static final int STREAM_ALARM = AudioSystem.STREAM_ALARM;
    /** The audio stream for notifications */
    public static final int STREAM_NOTIFICATION = AudioSystem.STREAM_NOTIFICATION;
    /** @hide The audio stream for phone calls when connected to bluetooth */
    public static final int STREAM_BLUETOOTH_SCO = AudioSystem.STREAM_BLUETOOTH_SCO;
    /** @hide The audio stream for enforced system sounds in certain countries (e.g camera in Japan) */
    public static final int STREAM_SYSTEM_ENFORCED = AudioSystem.STREAM_SYSTEM_ENFORCED;
    /** The audio stream for DTMF Tones */
    public static final int STREAM_DTMF = AudioSystem.STREAM_DTMF;
    /** @hide The audio stream for text to speech (TTS) */
    public static final int STREAM_TTS = AudioSystem.STREAM_TTS;

根据您的需要,您可以在此处更改流,例如 STREAM_MUSIC:

您可以使用 AudioSytem 类中的 refelction 获得常量值:

 private int getStreamType(String streamName) 
        final String streamSourceClassName = "android.media.AudioSystem";
        int streamType = 0;
        try 
            streamType = (int) Class.forName(streamSourceClassName).getDeclaredField(streamName).get(null);
         catch (ClassNotFoundException | IllegalAccessException | NoSuchFieldException e) 
            e.printStackTrace();
        
        return streamType;
    


audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

seekbar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));

seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() 
  @Override
  public void onProgressChanged(SeekBar seekBar, int newVolume, boolean b) 
    textview.setText("Media Volume : " + newVolume);
    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, 0);
  

  @Override
  public void onStartTrackingTouch(SeekBar seekBar) 

  @Override
  public void onStopTrackingTouch(SeekBar seekBar) 
);

【讨论】:

【参考方案4】:

跟进jesu的解决方案,如果您想在Service而不是Activity中更改音量,请替换:

AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);

与:

AudioManager audioManager;
audioManager = (AudioManager) YourServiceName.this.getSystemService(Context.AUDIO_SERVICE);

【讨论】:

【参考方案5】:

如果你的类型是AudioManager.STREAM_MUSIC:使用这个代码,按手机音量键

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) 
    switch (keyCode) 
    case KeyEvent.KEYCODE_VOLUME_UP:
        audio.adjustStreamVolume(
            AudioManager.STREAM_MUSIC,
            AudioManager.ADJUST_RAISE,
            AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        audio.adjustStreamVolume(
            AudioManager.STREAM_MUSIC,
            AudioManager.ADJUST_LOWER,
            AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
        return true;
    default:
        break;
    
    return super.onKeyDown(keyCode, event);

【讨论】:

【参考方案6】:

此代码将在按下 buttonSES 时立即将音量设置为 100,而不会向用户反馈。

public void perform_actionSES(View v) 
Button buttonSES = (Button) findViewById(R.id.buttonSES);

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 100, 0);  

【讨论】:

【参考方案7】:

各位程序员。我试图使代码尽可能简单。我希望这对某人有帮助。祝你有美好的一天!

我正在使用: 安卓工作室 4.2.2 构建 #AI-202.7660.26.42.7486908,构建于 2021 年 6 月 24 日 运行时版本:11.0.8+10-b944.6842174 amd64 虚拟机:OpenJDK 64 位服务器虚拟机(不适用) 视窗 10 10.0

对于 MainActivity.java,这里是代码。

package com.tutorial.android.mediaplayertest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;

import android.media.AudioManager;
import android.media.MediaPlayer;

import android.os.Bundle;
import android.widget.Button;

import android.widget.Toast;


public class MainActivity extends AppCompatActivity 

    private MediaPlayer mediaPlayer;
    private AudioManager audioManager;
    private Button play, pause, decVolume, incVolume;


    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // I want my media player instantiated as soon as the app starts
        mediaPlayer = MediaPlayer.create(this, R.raw.test);

        // play button
        play = findViewById(R.id.play_button);
        play.setOnClickListener(view -> 

            Toast.makeText(this, "Music Start", Toast.LENGTH_SHORT).show();

            mediaPlayer.start();
        );

        // pause button
        pause = findViewById(R.id.pause_button);
        pause.setOnClickListener(view -> 

            Toast.makeText(this, "Pause", Toast.LENGTH_SHORT).show();

            mediaPlayer.pause();
        );


        audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);

        // volume down button
        decVolume = findViewById(R.id.volume_down);
        decVolume.setOnClickListener(view -> 
            Toast.makeText(this, "Volume down", Toast.LENGTH_SHORT).show();
            audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
        );

        // volume up button
        incVolume = findViewById(R.id.volume_up);
        incVolume.setOnClickListener(view -> 
            Toast.makeText(this, "Volume up", Toast.LENGTH_SHORT).show();
            audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
        );
    



如果是activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/play_button"
        android:layout_
        android:layout_
        android:text="Play" />

    <Button
        android:id="@+id/pause_button"
        android:layout_
        android:layout_
        android:text="Pause" />

    <LinearLayout
        android:layout_
        android:layout_>

        <Button
            android:id="@+id/volume_down"
            android:layout_
            android:layout_
            android:text="-" />

        <Button
            android:layout_marginLeft="16dp"
            android:id="@+id/volume_up"
            android:layout_
            android:layout_
            android:text="+" />

    </LinearLayout>

</LinearLayout>
 

【讨论】:

【参考方案8】:
AudioManager aManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);


Button buttonUp= (Button) findViewById(R.id.upButton);
        buttonUp.setOnClickListener(new OnClickListener() 

            @Override
            public void onClick(View v) 
    enter code here

//To increase media player volume               
                `enter code here`aManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
            
        );

        Button downButton = (Button) findViewById(R.id.downButton);
        buttondown.setOnClickListener(new OnClickListener() 

            @Override
            public void onClick(View v) 

                aManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);             
            
        );

【讨论】:

仅仅发布源代码可能还不够(尽管它可能会解决问题)。请考虑添加一些解释,说明您发布的代码应该解决问题的原因。

以上是关于如何在 Android 中以编程方式增加和减少音量的主要内容,如果未能解决你的问题,请参考以下文章

如何在android中以编程方式设置ImageView的高度宽度?

如何以编程方式增加iPhone音量

如何在swift中以编程方式减少obj文件

如何以编程方式在 Android Q 中打开设置面板?

以编程方式获取 Android 手机型号,如何在 android 中以编程方式获取设备名称和型号?

如何在 Android 10 中以编程方式安装任何 Android 应用