最近几天被多媒体搞的头都大了,可能最近几天更新的都是和多媒体有关的,之前出现播放器放不出来歌,居然是环境的问题,想想也是伤感,
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();
}
}