如何在android中播放音频文件

我的android手机中有一个mp3文件,让它在我的sdcard中的某个地方是xyz.mp3。如何通过我的应用程序播放它?

4个解决方案
98 votes

只需使用MediaPlayer即可播放音频文件。 看看这个播放音频的好例子:

 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();
    }
}
Lalit Poptani answered 2020-02-21T19:32:03Z
8 votes

@Niranjan,如果您正在使用res / raw文件夹中的原始文件,即读取存储在项目中的文件,则可以使用:

mediaplayer.setDataSource(context, Uri.parse("android.resource://urpackagename/res/raw/urmp3name");

如果必须使用SD卡:

 MediaPlayer mediaPlayer = new MediaPlayer();
 File path = android.os.Environment.getExternalStorageDirectory();
 mediaPlayer.setDataSource(path + "urmp3filename");

请参阅此相关问题:Android上原始文件夹和sdcard之间的MediaPlayer问题

Suv answered 2020-02-21T19:32:32Z
2 votes
    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();
    }

}
Naren answered 2020-02-21T19:32:47Z
1 votes

如果音频在本地原始资源中:

MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
mediaPlayer.start(); // no need to call prepare(); create() does that for you

要从系统中本地可用的URI播放:

Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();
A-Sharabiani answered 2020-02-21T19:33:12Z
translate from https://stackoverflow.com:/questions/7291731/how-to-play-audio-file-in-android