Android multimedia apps play audio using mediaplayer

Android provides support for common audio and video formats. The supported audio formats include MP3 (. MP3), 3GPP (. 3gp), Ogg (. Ogg) and wave (. Ave), and the supported video formats include 3GPP (. 3gp) and MPEG-4 (. Mp4). Through the relevant methods provided by the Android API, audio and video playback can be realized in Android.

Here's how to play audio using mediaplayer

In Android, mediaplayer class is provided to play audio. Using MediaPlayer class to play audio is relatively simple. You only need to create objects of that class and specify the audio files to play, then call the start () method of the class.

1. Create mediaplayer object and load audio file

Both methods are implemented using mediaplayer's static method create(). a. Create (context, int resid) is loaded from the resource file, for example, mediaplayer player player = mediaplayer. Create (this, r.rwa. D);

b. Create (context, URI, URI) loads audio according to the specified URI, for example, mediaplayer player = mediaplayer. Create ("H") ttp://www.music @R_238_ 2419@.com /sound/bg.mp3");

When using the create () method, the audio has been loaded, but when using the parameterless construction method to create the mediaplayer object, you need to specify the resources to be loaded separately, which can be realized by using the setdatasource () method of the mediaplayer class.

After using the setdatasource () method to load the audio file, mediaplayer needs to call the prepare () method of mediaplayer to load the audio file. Use the parameterless construction method to create a mediaplayer object and load the specified audio file. You can use the following code:

2. Start or resume playback

Start playing or resume playing of paused audio player. Start();

3. Stop playing

You can stop the playing audio player. Stop();

4. Pause playback

You can pause the playing audio player. Pause();

The following is a small example to realize a simple music player including play, pause / continue and stop functions. Upload the audio file to be played to the music directory of SD card. The audio file to be played here is whistle.mp3 directory, as shown in the figure

Layout file, including a text information display control and three buttons (play, pause / continue and stop buttons) RES / layout / main.xml

MainActivity:

The playback effect is shown in the figure

The Pause effect is shown in the figure

Continue the effect as shown in the figure

The stop effect is shown in the figure

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>