简单的使用MediaPlayer

最近几天被多媒体搞的头都大了,可能最近几天更新的都是和多媒体有关的,之前出现播放器放不出来歌,居然是环境的问题,想想也是伤感,

MediaPlayer,属于播放音乐的一种,还有一种是SoundPool,下一篇文章会介绍。

一般来说,MediaPlayer可以说有两种播放音乐的方式,一种是通过setDataSource,然后就是同步或者异步prepare,还有一种就是通过create,据说create里面自己包含了prepare,所以我也不知道他们有什么区别,反正知道使用的方式就是了嘛,贴代码,如此简洁的代码都不能看懂的话,我也就没有什么办法了。

package com.example.musicdemo;

import java.io.File;
import java.io.IOException;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
	MediaPlayer myMediaPlayer;

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

		// playMusic3();
		// playMusic1();
		playMusic2();
		// actually ,there is a way that can use URL to play music,but i can't
		// find a right url ,you can try
	}

	private void playMusic3() {
		// actually this is the same with the first,just the parm is not the
		// same
		myMediaPlayer = MediaPlayer.create(this,
				Uri.fromFile(new File("/sdcard/ty.mp3")));
		myMediaPlayer.start();
	}

	private void playMusic2() {
		myMediaPlayer = new MediaPlayer();
		try {
			// Initialized the MediaPlayer
			myMediaPlayer.reset();
			// set the datasource path
			myMediaPlayer.setDataSource("/sdcard/ty.mp3");
			// synchronized load the music
			// myMediaPlayer.prepare();
			// Asynchronized load the music is much difficult,i will updata it
			// later
			// myMediaPlayer.prepareAsync();
			System.out.println("3333333333");
			myMediaPlayer.start();
			System.out.println("4444444444");
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void playMusic1() {
		// play the music by read the resource
		// rember the create is the method that belong to MediaPlayer,if you use
		// the MediaPlayer's object's way ,it will wrong
		myMediaPlayer = MediaPlayer.create(this, R.raw.ty);
		// if you use the way that called create to initialized the music,there
		// is no need for the method prepare,because create contains prepare
		myMediaPlayer.start();
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值