-1

このコードを使用してMediaPlayer androidを使用したいのですが、エラーが発生します。このコードを修正する方法がありますか、誰かがこれのより良い例を教えてくれますか?

try {

    MediaPlayer player = new MediaPlayer();
    player.setDataSource("/LFP/res/raw/Allen.mp3");
    player.prepare();
    player.start();

} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}          
4

3 に答える 3

0
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import android.media.MediaPlayer.OnPreparedListener;
import android.view.MotionEvent;
import android.widget.MediaController;
import android.widget.TextView;

import java.io.IOException;

public class AudioPlayer extends Activity implements OnPreparedListener,                
MediaController.MediaPlayerControl{
private static final String TAG = "AudioPlayer";

public static final String AUDIO_FILE_NAME = "audioFileName";

private MediaPlayer mediaPlayer;
private MediaController mediaController;
private String audioFile;

private Handler handler = new Handler();

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_player);

audioFile = this.getIntent().getStringExtra(AUDIO_FILE_NAME);
((TextView)findViewById(R.id.now_playing_text)).setText(audioFile);

mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);

mediaController = new MediaController(this);

try {
  mediaPlayer.setDataSource(audioFile);
  mediaPlayer.prepare();
  mediaPlayer.start();
} catch (IOException e) {
  Log.e(TAG, "Could not open file " + audioFile + " for playback.", e);
}

}

@Override
protected void onStop() {
super.onStop();
mediaController.hide();
mediaPlayer.stop();
mediaPlayer.release();
}

  @Override
  public boolean onTouchEvent(MotionEvent event) {

  mediaController.show();
  return false;
}

public void start() {
mediaPlayer.start();
}

public void pause() {
mediaPlayer.pause();
}

public int getDuration() {
return mediaPlayer.getDuration();
}

public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}

public void seekTo(int i) {
mediaPlayer.seekTo(i);
}

public boolean isPlaying() {
return mediaPlayer.isPlaying();
}

public int getBufferPercentage() {
return 0;
}

public boolean canPause() {
return true;
}

public boolean canSeekBackward() {
return true;
}

public boolean canSeekForward() {
return true;
}

  public void onPrepared(MediaPlayer mediaPlayer) {
  Log.d(TAG, "onPrepared");
  mediaController.setMediaPlayer(this);
  mediaController.setAnchorView(findViewById(R.id.main_audio_view));

   handler.post(new Runnable() {
     public void run() {
     mediaController.setEnabled(true);
     mediaController.show();
     }
   });
  }
 }

これは私にとってはうまくいきました。あなたにとってもうまくいくことを願っています。

于 2013-05-30T09:21:33.887 に答える