在Android音乐播放器中播放音频文件

时间:2013-01-19 08:56:13

标签: android

我的Android Project的原始文件夹中有一些音频文件。我希望通过Android的默认音乐播放器播放这些音频文件。有人可以共享一些示例代码段来解释该过程。

5 个答案:

答案 0 :(得分:1)

Intent intent = new Intent(android.content.Intent.ACTION_VIEW);

Uri data = Uri.parse("file://"+Environment.getExternalStorageDirectory()
        .getAbsolutePath()+"/" + fileName);
String type = "audio/mp3";
intent.setDataAndType(data, type);
startActivity(intent);

fileName是您SDCard上的音频名称。

答案 1 :(得分:1)

首先声明MediaPlayer对象:

MediaPlayer mSoundPlayer;

添加此功能:

//Play music
    public void playSound(int id){
            try{
                mSoundPlayer = MediaPlayer.create(mContext, id);
                mSoundPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer arg0) {
                        mSoundPlayer.start();

                    }

                });
                mSoundPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener () {

                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        // TODO Auto-generated method stub
                        mSoundPlayer.release();
                    }});
            }
            catch (Exception e) {
                // TODO: handle exception
                Log.v("Sound Exception","Sound Exception = "+e.getMessage());
            }
    }

打电话:

playSound(R.raw.sound1);

发布MediaPlayer

是一个好习惯
    @Override
    public void onPause(){
        super.onPause();
        if(mSoundPlayer!=null)
            mSoundPlayer.release();
    }

感谢。

答案 2 :(得分:1)

以下是示例代码段...

For playing audio files in android

Playing audio

public void splashPlayer() {
 VideoView videoHolder = new VideoView(this);
 setContentView(videoHolder);
 Uri video = Uri.parse("android.resource://" + getPackageName() + "/"
    + R.raw.splash);
 videoHolder.setVideoURI(video);
 videoHolder.setOnCompletionListener(new OnCompletionListener() {
  public void onCompletion(MediaPlayer mp) {
   jumpMain(); //jump to the next Activity
  }
 });
 videoHolder.start();
}

有关完整教程,请转到this

答案 3 :(得分:1)

我尝试了这段代码: -

button.setOnClickListener(new OnClickListener() 
{

@Override
public void onClick(View v) 
{
Uri uri = Uri.parse("R.raw.fashion.mp3");//the audio file
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent); 

}
});

但是当我运行这段代码时;应用程序崩溃,LogCat显示:“ActivityNotFoundException”...找不到处理意图的活动。

答案 4 :(得分:-1)

尝试这可能有帮助。

Uri data = Uri.parse("file://"+Environment.getExternalStorageDirectory()
                .getAbsolutePath()+"/" + audioName);
        Intent intent = new Intent(android.content.Intent.ACTION_VIEW, data);

        String type = "audio/mp3";
        intent.setDataAndType(data, type);
        startActivity(intent);