Menu Home

MediaPlayer(一)——处理网络音频文件

Android MediaPlayer状态转换图

图片来自Google Android Doc

图片来自Google Android Doc

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/TV01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Status :" />

    <TextView
        android:id="@+id/statusTV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Unknown" />

    <TextView
        android:id="@+id/bufferPercentTV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Buffer Percentage : " />

    <ProgressBar
        android:id="@+id/bufferSB"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:max="100" />

    <Button
        android:id="@+id/startBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start" />

    <Button
        android:id="@+id/stopBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop" />

</LinearLayout>

main_activity.java

public class MainActivity extends Activity implements OnCompletionListener,
		OnBufferingUpdateListener, OnClickListener, OnPreparedListener,
		OnErrorListener {

	Button startBtn;
	Button stopBtn;
	TextView statusTV;
	ProgressBar bufferSB;
	MediaPlayer mediaPlayer;

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

		startBtn = (Button) findViewById(R.id.startBtn);
		startBtn.setOnClickListener(this);
		startBtn.setEnabled(false);

		stopBtn = (Button) findViewById(R.id.stopBtn);
		stopBtn.setOnClickListener(this);
		stopBtn.setEnabled(false);

		statusTV = (TextView) findViewById(R.id.statusTV);
		statusTV.setText("Creating mediaPlayer");

		bufferSB = (ProgressBar) findViewById(R.id.bufferSB);

		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnCompletionListener(this);
		mediaPlayer.setOnBufferingUpdateListener(this);
		mediaPlayer.setOnPreparedListener(this);
		mediaPlayer.setOnErrorListener(this);

		statusTV.setText("Created mediaPlayer");

		statusTV.setText("seting DataSource");
		try {
			mediaPlayer.setDataSource("http://lnmcc.net/wordpress/wp-content/uploads/2013/10/Rolling-In-The-Deep.mp3");
			statusTV.setText("setted DataSource");

			statusTV.setText("calling prepareAsync");
			// 不同于prepare(), prepareAsync()会立即返回,后台开始缓冲
			mediaPlayer.prepareAsync();
		} catch (IOException e) {
			Log.v("mediaPlayer.setDataSource", e.getMessage());
		}
	}

	@Override
	public void onClick(View v) {

		if (v == startBtn) {
			mediaPlayer.start();
			statusTV.setText("start play");

			startBtn.setEnabled(false);
			stopBtn.setEnabled(true);
		} else if (v == stopBtn) {
			mediaPlayer.pause();
			statusTV.setText("pause play");

			stopBtn.setEnabled(false);
			startBtn.setEnabled(true);
		}
	}

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {

		statusTV.setText("invoke onError");

		switch (what) {
		case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
			statusTV.setText("MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK" + extra);
			break;
		case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
			statusTV.setText("MEDIA_ERROR_SERVER_DIED" + extra);
			break;
		case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
			statusTV.setText("MEDIA_ERROR_UNSUPPORTED" + extra);
			break;
		case MediaPlayer.MEDIA_ERROR_UNKNOWN:
			statusTV.setText("MEDIA_ERROR_UNKNOWN" + extra);
			break;
		}
		return false;
	}

	@Override
	public void onCompletion(MediaPlayer mp) {

		statusTV.setText("invoke onCompletion");
		stopBtn.setEnabled(false);
		startBtn.setEnabled(true);
	}

	@Override
	// 当后台缓冲数据发生变化时,会调用这个方法
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		bufferSB.setProgress(percent);
	}
	
	@Override
	//数据缓冲完成,可以播放
	public void onPrepared(MediaPlayer mp) {
		
		statusTV.setText("invoke onPrepared");
		startBtn.setEnabled(true);
	}

}

最后要在AndroidManifest.xml中加入Internet权限:

<uses-permission android:name="android.permission.INTERNET" />

git clone https://github.com/lnmcc/NetAudioPlayerExample.git

12 replies

  1. I precisely wished to appreciate you yet again. I am not sure the things that I would have handled without those tactics shown by you about this subject matter. Certainly was a distressing concern in my circumstances, nevertheless taking a look at the very specialised strategy you solved the issue forced me to weep for gladness. I’m grateful for your assistance and then hope you are aware of a powerful job you were undertaking instructing many others all through your site. I am certain you’ve never encountered any of us.

  2. I enjoy you because of your own labor on this web page. Betty loves doing internet research and it’s really obvious why. Many of us notice all of the lively form you present worthwhile solutions by means of this blog and as well invigorate contribution from website visitors about this idea plus our own daughter is really discovering a whole lot. Have fun with the remaining portion of the year. You’re the one carrying out a splendid job.

  3. My husband and i have been excited Michael could do his reports with the ideas he came across through the blog. It is now and again perplexing just to possibly be handing out points that others could have been making money from. And we all understand we now have the writer to be grateful to for this. All of the explanations you have made, the simple blog navigation, the friendships your site help foster – it’s many fabulous, and it’s helping our son and us reason why the issue is brilliant, and that is exceedingly important. Thank you for all!

  4. My husband and i have been quite comfortable when Albert managed to conclude his analysis from your precious recommendations he discovered using your weblog. It’s not at all simplistic to just possibly be giving out concepts that men and women have been trying to sell. Therefore we figure out we need the blog owner to be grateful to for that. Those explanations you’ve made, the simple website navigation, the relationships your site make it possible to foster – it’s got everything remarkable, and it’s really letting our son in addition to our family reckon that the matter is brilliant, and that is pretty serious. Thank you for the whole lot!

  5. My wife and i have been now fulfilled Chris could round up his basic research with the ideas he made in your web site. It’s not at all simplistic to just choose to be giving out thoughts which the others could have been trying to sell. And we all recognize we’ve got the blog owner to thank for this. The entire explanations you made, the easy web site navigation, the friendships you make it possible to foster – it is mostly incredible, and it’s really facilitating our son and our family imagine that that concept is fun, and that’s incredibly essential. Thank you for everything!

  6. I wanted to jot down a quick comment to be able to say thanks to you for these fantastic tactics you are giving out at this website. My time intensive internet lookup has at the end of the day been compensated with wonderful knowledge to write about with my best friends. I ‘d believe that many of us website visitors are rather blessed to dwell in a very good community with many awesome individuals with helpful advice. I feel truly privileged to have encountered your entire webpage and look forward to so many more pleasurable minutes reading here. Thank you once again for a lot of things.

  7. Thanks for each of your effort on this web page. My daughter delights in going through investigations and it’s simple to grasp why. Almost all know all relating to the compelling means you create functional thoughts through the web blog and as well recommend response from some others about this article and my child is actually becoming educated a great deal. Have fun with the rest of the new year. You’re conducting a fantastic job.

  8. I just wanted to compose a brief comment so as to say thanks to you for those stunning advice you are posting on this website. My time consuming internet research has now been honored with excellent facts and strategies to exchange with my family. I would assume that we website visitors are quite blessed to dwell in a very good website with very many perfect individuals with good hints. I feel rather fortunate to have come across your entire site and look forward to some more brilliant moments reading here. Thanks once more for all the details.

  9. I precisely wanted to thank you so much yet again. I am not sure the things I might have undertaken without those solutions discussed by you relating to such a situation. Entirely was a frustrating condition in my circumstances, nevertheless viewing the very expert manner you resolved the issue forced me to cry with contentment. I am thankful for your work and in addition believe you realize what an amazing job you are always accomplishing training the rest through your websites. I’m certain you’ve never come across all of us.

  10. Thanks so much for giving everyone a very breathtaking opportunity to read in detail from this site. It’s always so fantastic and packed with a lot of fun for me personally and my office acquaintances to visit your web site nearly 3 times per week to learn the fresh issues you will have. And of course, I am just certainly motivated with your striking tactics you give. Selected two facts in this post are truly the simplest we have ever had.

  11. My wife and i ended up being so more than happy that Ervin could finish off his survey with the ideas he obtained from your own web pages. It’s not at all simplistic just to choose to be giving for free secrets and techniques most people may have been selling. And we know we have got the writer to appreciate for that. All the illustrations you have made, the simple site menu, the relationships you give support to instill – it’s got most amazing, and it is making our son in addition to the family do think the subject is amusing, and that is truly fundamental. Many thanks for all!

  12. I simply wanted to make a remark to say thanks to you for all of the pleasant advice you are sharing on this site. My particularly long internet lookup has at the end been paid with reliable strategies to share with my best friends. I would suppose that we readers actually are very endowed to dwell in a great website with many brilliant professionals with good strategies. I feel quite blessed to have encountered your weblog and look forward to plenty of more exciting minutes reading here. Thanks a lot once again for all the details.

Leave a Reply

Your email address will not be published.