In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "Android how to use MediaPlayer to play audio", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "Android how to use MediaPlayer to play audio" this article.
This paper mainly introduces the way to play audio with MediaPlayer. For the basics of MediaPlayer, such as status, refer to the introduction to the basics of Android MediaPlayer.
For ease of expression, the variable is defined as mediaPlayer.
How to use MediaPlayer
Create MediaPlayer
You can either new MediaPlayer directly or create it using the create method provided by MediaPlayer.
MediaPlayer = new MediaPlayer ()
After a successful creation using the create method, the mediaPlayer is in the Prepared state. It can be played directly by start.
MediaPlayer = MediaPlayer.create (getApplicationContext (), Uri.fromFile (file)); mediaPlayer.start ()
Set the audio source-setDataSource
Set the sound source by calling setDataSource. SetDataSource has several overloading methods. Let's take a look at a few commonly used methods.
For example, set up to use resources in assets. The actual situation may require try catch.
AssetFileDescriptor fd = null;MediaPlayer mediaPlayer = new MediaPlayer (); fd = context.getApplicationContext (). GetAssets (). OpenFd (name); mediaPlayer.setDataSource (fd.getFileDescriptor (), fd.getStartOffset (), fd.getLength ())
Local file, the absolute path of the file is required.
MediaPlayer.setDataSource (file.getAbsolutePath ())
Or get the Uri of the file to create the mediaPlayer.
MediaPlayer = MediaPlayer.create (getApplicationContext (), Uri.fromFile (file))
Set the network audio, also use the setDataSource method, set url.
MediaPlayer.setDataSource ("https://demo.com/sample.mp3"));"
When playing network audio, if you are using http, you may get an error
Java.io.IOException: Cleartext HTTP traffic to demo.com not permitted
You can simply set manifest and set usesCleartextTraffic= "true"
Ready-prepare
Prepare audio resources synchronously and asynchronously. PrepareAsync () is asynchronous, and prepare is synchronous. Pay attention to thread scheduling problems and do not block UI threads.
Prepare audio asynchronously, often in conjunction with MediaPlayer.OnPreparedListener listeners. Other settings can also be made when preparing asynchronously.
MediaPlayer.prepareAsync (); mediaPlayer.setOnPreparedListener (new MediaPlayer.OnPreparedListener () {@ Override public void onPrepared (MediaPlayer mediaPlayer) {mediaPlayer.start (); / / play} when ready)
Play in a loop-Looping
Sets the loop playback setLooping.
MediaPlayer.setLooping (true)
When the playback is finished, the OnCompletionListener will not be called back, but the current audio will be played from scratch.
Play-start
To play the audio, call the start method.
MediaPlayer.start ()
When you are in the Prepared,Pause and PlaybackComplete states, you can call the start method to enter the Started state.
Pause-pause
Pause playback and use the pause method. Check whether the mediaPlayer is playing before pausing.
If (mediaPlayer.isPlaying ()) {mediaPlayer.pause ();}
If the pause succeeds, it is in the Paused state.
Stop-stop
Reviewing the diagram of MediaPlayer status switch, we can see that in the three states of playback, pausing and playback completion, you can call the stop method to enter the Stopped state.
MediaPlayer.stop ()
Adjust the schedule-seekTo
Adjust the playback progress. We usually use music playback software will have this function. The seekTo method accepts a millisecond argument.
Int targetMS = (int) (percent * mediaPlayer.getDuration ()); mediaPlayer.seekTo (targetMS)
SeekTo does not change the state of MediaPlayer.
Int targetMS = (int) (percent * mediaPlayer.getDuration ()); mediaPlayer.seekTo (targetMS)
The mediaPlayer after reset enters the Idle state. Need to reset the sound source and preparation.
Release-release
When you no longer use this mediaPlayer, you should release it as soon as possible to release related resources.
After calling release, mediaPlayer enters the End state. At this point, the mediaPlayer can no longer be used.
Common listener
Buffer listener OnBufferingUpdateListener
For example, when we load network audio, we often use this listener to monitor the buffer progress. Show buffering progress, which can also improve the user experience.
MMediaPlayer.prepareAsync (); mMediaPlayer.setOnBufferingUpdateListener (new MediaPlayer.OnBufferingUpdateListener () {@ Override public void onBufferingUpdate (MediaPlayer mp, int percent) {/ / percent represents buffer percentage}})
Error listener OnErrorListener
MediaPlayer.setOnErrorListener (new MediaPlayer.OnErrorListener () {@ Override public boolean onError (MediaPlayer mediaPlayer, int I, int i1) {return true; / / returns true indicates that an error was made here and onCompletion}} will not be called back)
Notice the return value of onError. You can choose to handle the error yourself.
* @ return True if the method handled the error, false if it didn't. * Returning false, or not having an OnErrorListener at all, will * cause the OnCompletionListener to be called. * / boolean onError (MediaPlayer mp, int what, int extra)
Listener OnCompletionListener after playback
MediaPlayer.setOnCompletionListener (new MediaPlayer.OnCompletionListener () {@ Override public void onCompletion (MediaPlayer mediaPlayer) {/ / playback completed}})
Use the example
Play audio from assets
Play the audio file in assets, using the AssetFileDescriptor class. Remember to turn off AssetFileDescriptor after use.
Private void playAssetsAudio (final String name, Context context) {Log.d (TAG, "playAssetWordSound: try to play assets sound file. -> "+ name); AssetFileDescriptor fd = null; try {MediaPlayer mediaPlayer; Log.v (TAG," Looking in assets. "); fd = context.getApplicationContext (). GetAssets (). OpenFd (name); mediaPlayer = new MediaPlayer (); mediaPlayer.reset (); mediaPlayer.setDataSource (fd.getFileDescriptor (), fd.getStartOffset (), fd.getLength ()); mediaPlayer.prepareAsync (); mediaPlayer.setOnPreparedListener (new MediaPlayer.OnPreparedListener ()) {@ Override public void onPrepared (MediaPlayer mediaPlayer) {Log.d (TAG," onPrepared: "+ name) MediaPlayer.start (); mediaPlayer.setOnCompletionListener (new MediaPlayer.OnCompletionListener () {@ Override public void onCompletion (MediaPlayer mp) {mp.release (); Log.d (TAG, "onCompletion:" + name);}}); mediaPlayer.setOnErrorListener (new MediaPlayer.OnErrorListener () {@ Override public boolean onError (MediaPlayer mp, int I, int i1) {mp.release (); return true;}}) } catch (Exception e) {try {if (fd! = null) {fd.close ();}} catch (Exception E1) {Log.e (TAG, "Exception close fd:", E1);}} finally {if (fd! = null) {try {fd.close ();} catch (IOException e) {Log.e (TAG, "Finally, close fd", e);}}}
Play local audio files
Try to play the audio file. Play it only once.
Private void playAudioFile (final File file) {Log.d (TAG, "playAudioFile:" + file.getAbsolutePath ()); MediaPlayer mediaPlayer; try {mediaPlayer = new MediaPlayer (); mediaPlayer.setLooping (false); mediaPlayer.setDataSource (file.getAbsolutePath ()); mediaPlayer.prepare (); mediaPlayer.start (); mediaPlayer.setOnCompletionListener (new MediaPlayer.OnCompletionListener () {@ Override public void onCompletion (MediaPlayer mp) {mp.release ();}})) MediaPlayer.setOnErrorListener (new MediaPlayer.OnErrorListener () {@ Override public boolean onError (MediaPlayer mediaPlayer, int I, int i1) {Log.d (TAG, "Play local sound onError:" + I + "," + i1); return true;}});} catch (Exception e) {Log.e (TAG, "playAudioFile:", e);}}
Play online audio
Set url to play online audio
Private void playOnlineSound (String soundUrlDict) {try {MediaPlayer mediaPlayer = new MediaPlayer (); mediaPlayer.setDataSource (soundUrlDict); mediaPlayer.prepareAsync (); mediaPlayer.setOnPreparedListener (new MediaPlayer.OnPreparedListener () {@ Override public void onPrepared (MediaPlayer mediaPlayer) {mediaPlayer.start ();}}); mediaPlayer.setOnCompletionListener (new MediaPlayer.OnCompletionListener () {@ Override public void onCompletion (MediaPlayer mp) {if (mp! = null) {mp.release ();} Log.d (TAG, "onCompletion: play sound.");}})) MediaPlayer.setOnErrorListener (new MediaPlayer.OnErrorListener () {@ Override public boolean onError (MediaPlayer mediaPlayer, int I, int i1) {Log.d (TAG, "Play online sound onError:" + I + "," + i1); return false;}});} catch (IOException E1) {Log.e (TAG, "url:", E1);}}
The above is all the content of the article "how to play Audio in Android using MediaPlayer". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.