The AudioManager class is used in Android App to write an audio player

  • 2021-07-01 08:17:23
  • OfStack

Mobile phones have sound mode, sound, mute and vibration, and even both vibration and sound, which are the basic functions of mobile phones. In Android mobile phone, we can also manage the sound mode and adjust the sound size through the sound management interface provided by SDK of Android, which is the use of AudioManager in Android.
The AudioManager class is in the android. Media package and provides access to control volume and tone mode operations

The following are the methods for AudioManager to set sound mode and adjust sound size.


How to get the sound manager:


AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);


The main methods inside:
A, set sound mode


// Sound mode  
AudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
// Silent mode  
AudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
// Vibration mode  
AudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);


B, adjust sound size


// Reduce the sound volume  
AudioManager.adjustVolume(AudioManager.ADJUST_LOWER, 0);
// Turn up the sound volume  
AudioManager.adjustVolume(AudioManager.ADJUST_RAISE, 0) ; 
 (When the incoming 1 Parameters are  AudioManager.ADJUST_LOWER  You can turn down the volume when 1 Units, passed in  AudioManager.ADJUST_RAISE  You can turn up the volume 1 Units.) 

C, getMode () Get audio mode
D, getRingerMode () Acquire Ringtone Vibration Pattern


public void setStreamMute (int streamType, boolean state)


Mute or unmuted audio stream:
The mute command is protected from client process death: If a process with an active mute request on a stream dies, the stream is automatically unmuted.
For a given stream, mute requests are cumulative: AudioManager receives several mute requests from one or more clients, and the stream is unmuted only when the same number of unmute requests are received.
For a better user experience, the program must cancel the muted stream in onPause () and mute it again in onResume () if appropriate

This method can only be used for platform-wide management applications or primary telephony applications that replace audio settings.

Invoke the example:


import android.app.Activity; 
import android.app.Service; 
import android.media.AudioManager; 
import android.media.MediaPlayer; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.CompoundButton; 
import android.widget.CompoundButton.OnCheckedChangeListener; 
import android.widget.ToggleButton; 
 
public class AutoActivity extends Activity { 
  Button play, up, down,stop; 
  ToggleButton mute; 
  AudioManager aManager; 
  MediaPlayer mPlayer; 
  boolean flag = true; 
 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_auto); 
 
    aManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE); 
    play = (Button) findViewById(R.id.playBtn); 
    up = (Button) findViewById(R.id.upBtn); 
    down = (Button) findViewById(R.id.downBtn); 
    stop = (Button) findViewById(R.id.stopBtn); 
    mute = (ToggleButton) findViewById(R.id.silenceBtn); 
    //  Initialization MediaPlayer Object, ready to play music  
    mPlayer = MediaPlayer.create(AutoActivity.this, 
        R.raw.love); 
 
    play.setOnClickListener(new OnClickListener() { 
      // Music play and pause  
      @Override 
      public void onClick(View v) { 
         
        //  Set up loop playback  
        if(flag) { 
          play.setText(" Suspend "); 
          mPlayer.setLooping(true);// Circular playing of music  
          mPlayer.start(); 
          flag = false; 
        }else { 
          play.setText(" Play "); 
          mPlayer.pause(); 
          flag = true; 
        } 
      } 
    }); 
    up.setOnClickListener(new OnClickListener() { 
      // Raise the volume  
      @Override 
      public void onClick(View v) { 
        //  Specifies to adjust the audio of music and increase the volume , And the real volume graphics indicate  
        aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, 
            AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI); 
      } 
    }); 
    down.setOnClickListener(new OnClickListener() { 
      // Reduce the volume  
      @Override 
      public void onClick(View v) { 
        //  Specifies to adjust the audio of music and reduce the volume , And the real volume graphics indicate  
        aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, 
            AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI); 
      } 
    }); 
    stop.setOnClickListener(new OnClickListener() { 
      // Stop the music  
      @Override 
      public void onClick(View v) { 
        mPlayer.stop(); 
        play.setText(" Play "); 
        flag = true; 
        mPlayer = MediaPlayer.create(AutoActivity.this, 
            R.raw.love); 
      } 
    }); 
    mute.setOnCheckedChangeListener(new OnCheckedChangeListener() { 
      // Mute function  
      @Override 
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
        aManager.setStreamMute(AudioManager.STREAM_MUSIC, isChecked); 
      } 
    }); 
  } 
 
} 

Interface layout file, activity_auto. xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="fill_parent" 
  android:layout_height="wrap_content" > 
 
  <TableLayout 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_marginTop="360dp" > 
 
    <TableRow> 
 
      <Button 
        android:id="@+id/playBtn" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:layout_weight="1" 
        android:text=" Play " /> 
 
      <Button 
        android:id="@+id/stopBtn" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:layout_weight="1" 
        android:text=" Stop " /> 
    </TableRow> 
 
    <TableRow> 
 
      <Button 
        android:id="@+id/upBtn" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:layout_weight="1" 
        android:text="VOL+" /> 
 
      <Button 
        android:id="@+id/downBtn" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:layout_weight="1" 
        android:text="VOL-" /> 
 
      <ToggleButton 
        android:id="@+id/silenceBtn" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:layout_weight="1" 
        android:text=" Silence " 
        android:textColor="#ff0000" /> 
    </TableRow> 
  </TableLayout> 
 
</LinearLayout> 

The program is relatively simple, only a few simple function buttons, but it is enough to understand the usage ~

The use mode and method of MediaPlayer, specifically:
1) How to get an MediaPlayer instance:
You can use direct new:


  MediaPlayer mp = new MediaPlayer();

You can also use create methods, such as:


MediaPlayer mp = MediaPlayer.create(this, R.raw.test);// At this time, you don't have to call setDataSource It's over 


2) How to set the files to play:
The files to be played by MediaPlayer mainly include three sources:
a. resource resources that users bring in advance in their applications
For example:


MediaPlayer.create(this, R.raw.test);

b. Media files stored in an SD card or other file path
For example:


mp.setDataSource("/sdcard/test.mp3");

c. Media Files on the Network
For example:


// Sound mode  
AudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
// Silent mode  
AudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
// Vibration mode  
AudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
0


There are four methods of setDataSource1 in MediaPlayer:

setDataSource (String path) setDataSource (FileDescriptor fd) setDataSource (Context context, Uri uri) setDataSource (FileDescriptor fd, long offset, long length)

3) The main control method of the player:
Android controls the playback of the media file by controlling the state of the player, wherein:
prepare () and prepareAsync () provide synchronous and asynchronous ways to set the player into prepare state. It should be noted that if the MediaPlayer instance is created by create method, there is no need to call prepare () before starting playback for the first time, because it has already been called in create method.
start () is the way to actually start file playback,
pause () and stop () are relatively simple and serve to pause and stop playing.
seekTo () is a positioning method, which allows the player to start playing from the specified position. It should be noted that this method is an asynchronous method, that is to say, when the method returns, it does not mean that the positioning is completed, especially for the played network files. When the real positioning is completed, OnSeekComplete. onSeekComplete () will be triggered. If necessary, setOnSeekCompleteListener (OnSeekCompleteListener) can be called to set the listener for processing.
release () can release the resources occupied by the player, and 1 should call it as soon as possible when it is determined that the player is no longer used.
reset () enables the player to recover from the Error state and return to the Idle state.


4) Set the listener for the player:
MediaPlayer provides a set of different listener methods to better monitor the working state of the player in order to deal with various situations in time,
For example, setOnCompletionListener (MediaPlayer. OnCompletionListener listener),
setOnErrorListener (MediaPlayer. OnErrorListener listener), etc., when setting the player, it is necessary to consider the possible situations of the player and set up the monitoring and processing logic to keep the robustness of the player.


Related articles: