The Android app uses the Audiomanager class to write audio players _android

Source: Internet
Author: User
Tags prepare

Mobile phones have sound mode, sound, mute and vibration, and even vibration plus sound, these are the basic functions of mobile phones. On Android phones, we can also use the sound management interface provided by the Android SDK to manage the phone's sound mode and adjust the sound size, which is the Audiomanager of Android.
The Audiomanager class is located on Android. Media package, this class provides access to control volume and sound mode operation

The following are the Audiomanager ways to set the sound mode and adjust the sound size.


How to get the Sound manager:

Audiomanager Audiomanager = (audiomanager) getsystemservice (Audio_service);


The Main method inside:
A, set the sound mode

Sound mode 
audiomanager.setringermode (audiomanager.ringer_mode_normal);
Mute mode 
audiomanager.setringermode (audiomanager.ringer_mode_silent);
Vibration mode 
Audiomanager.setringermode (audiomanager.ringer_mode_vibrate);


B, adjust the sound size

Reduce sound volume 
audiomanager.adjustvolume (audiomanager.adjust_lower, 0);
Turn up the sound volume 
audiomanager.adjustvolume (audiomanager.adjust_raise, 0);
(when the first argument passed is Audiomanager.adjust_lower , you can turn the volume down one unit, and when you pass in the Audiomanager.adjust_raise, you may turn the volume up one unit. )

C, GetMode () Get audio mode
D, Getringermode () get the ring vibration mode

public void Setstreammute (int streamtype, Boolean state)


Mute or not mute the audio stream:
Mute commands are protected from client process death: If the process dies with an active mute request on the stream, the stream is automatically muted.
For a given stream, the mute request is cumulative: Audiomanager receives several mute requests from one or more clients, and the mute is Shireu only if the same number of cancellation requests is received.
For a better user experience, the program must remove the muted stream from the OnPause (), if appropriate, mute again in Onresume ()

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

Call 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); 
 
    Initialize the MediaPlayer object, ready to play music MPlayer = Mediaplayer.create (Autoactivity.this, R.raw.love); 
         
        Play.setonclicklistener (New Onclicklistener () {//music playback and pausing @Override public void OnClick (View v) { 
          Sets the loop play if (flag) {Play.settext (pause); 
          Mplayer.setlooping (TRUE);//Music Loop play Mplayer.start (); 
        Flag = false; 
          }else {Play.settext ("play"); 
          Mplayer.pause (); 
        Flag = true; 
    } 
      } 
    }); 
        Up.setonclicklistener (New Onclicklistener () {//Increase volume @Override public void OnClick (View v) { Specifies the audio that adjusts the music, increases the volume, and the realistic volume graph signals amanager.adjuststreamvolume (Audiomanager.stream_music, Audiomanager.adj 
      Ust_raise, AUDIOMANAGER.FLAG_SHOW_UI); 
    } 
    }); Down.setonclicklistener (New Onclicklistener () {//lower volume @Override public voID OnClick (View v) {//Specify the audio to tune the music, lower the volume, and the realistic volume graph to indicate Amanager.adjuststreamvolume (Audiomanager.stream_music, 
      Audiomanager.adjust_lower, AUDIOMANAGER.FLAG_SHOW_UI); 
    } 
    }); 
        Stop.setonclicklistener (New Onclicklistener () {//stop 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 Onchecke Dchanged (Compoundbutton Buttonview, Boolean ischecked) {Amanager.setstreammute (Audiomanager.stream_music, ISCHEC 
      ked); 
  } 
    }); 
 } 
 
}

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 and 
        Roid: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/u Pbtn "android:layout_width=" fill_parent "android:layout_height=" Wrap_content "Android:layout_we" ight= "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_hei ght= "Wrap_content" android:layout_weight= "1" android:text= "mute" android:textcolor= "#ff0000"/&gt 
    ; 
 </TableRow> </TableLayout> </LinearLayout>

The program is simple, only a few simple function buttons, but the use of understanding is enough ~

MediaPlayer the way and method of use, specifically:
1 How to obtain MediaPlayer example:
You can use the direct new method:

  MediaPlayer MP = new MediaPlayer ();

You can also use the method of create, such as:

MediaPlayer MP = Mediaplayer.create (this, r.raw.test);/Then you don't have to call Setdatasource.


2 How to set the file to play:
MediaPlayer the files to be played mainly include 3 sources:
A. Resource resources that users have taken in advance from their applications
For example:

Mediaplayer.create (this, r.raw.test);

B. media files stored in SD card or other file path
For example:

Mp.setdatasource ("/sdcard/test.mp3");

C. media files on the network
For example:

Mp.setdatasource ("Http://www.citynorth.cn/music/confucius.mp3");


MediaPlayer's Setdatasource altogether four methods:

    • Setdatasource (String Path)
    • Setdatasource (FileDescriptor FD)
    • Setdatasource (context context, URI Uri)
    • Setdatasource (filedescriptor fd, long offset, long length)

3) The main control method for the player:
Android controls the playback of media files by controlling the state of the player, where:
Prepare () and Prepareasync ()   Provides both synchronous and asynchronous ways to set the player into prepare state, it should be noted that if the MediaPlayer instance was created by the Create method, then the first time to start playback does not need to call prepare (), because the Create method has already been called.
Start () is the way to actually start a file playback.
Pause () and stop () are simpler to pause and stop playback,
Seekto () is a positioning method that allows the player to start playing from a specified location, and it is important to note that the method is an asynchronous method , which means that the method returns does not mean that the location is complete, especially the network file being played, which triggers onseekcomplete.onseekcomplete when the true location is complete (), and if necessary, can call Setonseekcompletelistener ( Onseekcompletelistener) set up the listener to handle.
Release () releases the resources that the player occupies and should be invoked as soon as possible when it is determined that the player is no longer in use. The
Reset () allows the player to recover from the error state and return to the idle state.
 
 
4) Set listener listeners:
   MediaPlayer provides a number of ways to set up different listeners to better monitor the player's working status in order to handle various situations in a timely manner.
such as: Setoncompletionlistener (Mediaplayer.oncompletionlistener listener),
Setonerrorlistener ( Mediaplayer.onerrorlistener listener), and so on, set the player to take into account the player may be the situation set up listening and processing logic to maintain the robustness of the player.
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.