how to play audio file in android

2019-01-07 11:33发布

I have a mp3 file in my android mobile, lets it's a xyz.mp3 somewhere in my sdcard. I want to play it through my application. Please help me I have no idea about it.

3条回答
劳资没心,怎么记你
2楼-- · 2019-01-07 11:36

@Niranjan, If you are using a raw file from res/raw folder, ie., reading a file stored inside the project, we can use:

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

If you have to use from SD card:

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

See this related question: MediaPlayer issue between raw folder and sdcard on android

查看更多
【Aperson】
3楼-- · 2019-01-07 11:48
    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();
    }

}
查看更多
够拽才男人
4楼-- · 2019-01-07 12:01

Simply you can use MediaPlayer and play the audio file. Check out this nice example for playing Audio:

 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();
    }
}
查看更多
登录 后发表回答