实例,播放res/raw文件夹下和assets文件夹下的mp3文件
复制hongdou.mp3文件到assets文件夹下,shijiandouqunale.mp3到res/raw下
activity_main.java
<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"
tools:context=".MainActivity"
android:orientation="vertical">
<Button android:id="@+id/rawBut"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="播放Raw下歌曲"/>
<Button android:id="@+id/assetsBut"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="播放assets下歌曲"/>
</LinearLayout>
MainActivity.java
package com.example.rawresourcetest;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
MediaPlayer mediaPlayer1=null;
MediaPlayer mediaPlayer2=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button rawBut=(Button) super.findViewById(R.id.rawBut);
Button assetsBut=(Button) super.findViewById(R.id.assetsBut);
//直接根据声音文件的ID来创建MediaPlayer
mediaPlayer1=MediaPlayer.create(this, R.raw.shijiandouqunale);
//获取应用的AssetManager
AssetManager am=getAssets();
try {
//获取指定文件对应的AssetFileDescriptor
AssetFileDescriptor afd=am.openFd("hongdou.mp3");
mediaPlayer2=new MediaPlayer();
//使用MediaPlayer加载指定的声音文件
mediaPlayer2.setDataSource(afd.getFileDescriptor());
mediaPlayer2.prepare();
} catch (Exception e) {
e.printStackTrace();
}
rawBut.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mediaPlayer1.start();
}
});
assetsBut.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mediaPlayer2.start();
}
});
}
}