how to play audio file in android
我的 android 手机中有一个 mp3 文件,让它成为我 sdcard 某处的 xyz.mp3。
如何通过我的应用程序播放它?
您只需使用
1 2 3 4 5 6 7 8 9 10 11 12 | public void audioPlayer(String path, String fileName){ //set up MediaPlayer MediaPlayer mp = new MediaPlayer(); try { mp.setDataSource(path + File.separator + fileName); mp.prepare(); mp.start(); } catch (Exception e) { e.printStackTrace(); } } |
如果音频在本地原始资源中:
1 2 | MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1); mediaPlayer.start(); // no need to call prepare(); create() does that for you |
从系统本地可用的 URI 播放:
1 2 3 4 5 6 | Uri myUri = ....; // initialize Uri here MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setDataSource(getApplicationContext(), myUri); mediaPlayer.prepare(); mediaPlayer.start(); |
@Niranjan,如果您使用的是 res/raw 文件夹中的原始文件,即读取存储在项目中的文件,我们可以使用:
1 | mediaplayer.setDataSource(context, Uri.parse("android.resource://urpackagename/res/raw/urmp3name"); |
如果必须从 SD 卡使用:
1 2 3 | MediaPlayer mediaPlayer = new MediaPlayer(); File path = android.os.Environment.getExternalStorageDirectory(); mediaPlayer.setDataSource(path +"urmp3filename"); |
请参阅此相关问题:Android 上原始文件夹和 sdcard 之间的 MediaPlayer 问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public class MainActivity extends Activity implements OnClickListener { Button play; MediaPlayer mp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setVolumeControlStream(AudioManager.STREAM_MUSIC); play=(Button)findViewById(R.id.button1); play.setOnClickListener(this); } @Override public void onClick(View arg0) { mp=MediaPlayer.create(getApplicationContext(),R.raw.song);// the song is a filename which i have pasted inside a folder **raw** created under the **res** folder.// mp.start(); } @Override protected void onDestroy() { mp.release(); super.onDestroy(); } } |
来自 https://stackoverflow.com/users/726863/lalit-poptani 的回放很棒,它第一次工作,但由于我以前有文件的完整路径,所以我这样做了
1 2 3 4 5 6 7 8 9 10 11 12 | public void audioPlayer(String path){ //set up MediaPlayer MediaPlayer mp = new MediaPlayer(); try { mp.setDataSource(path ); mp.prepare(); mp.start(); } catch (Exception e) { e.printStackTrace(); } } |
感谢 http://www.helloandroid.com/tutorials/how-play-video-and-audio-android