所以我有一个.mp3 in
资产文件夹(我计划稍后会有更多资源),我只需点击一下即可播放它:
public static MediaPlayer m = new MediaPlayer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button= (Button) findViewById(R.id.btnDrum);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
PlayMusic(v);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void PlayMusic(View v) throws IOException {
try {
if (m.isPlaying()) {
m.stop();
m.release();
m = new MediaPlayer();
}
AssetFileDescriptor descriptor = getAssets().openFd(Kit.KickDrum);
m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
m.prepare();
m.setVolume(1f, 1f);
m.setLooping(true);
m.start();
} catch (Exception e) {
e.printStackTrace();
}
}
然而,每次我尝试点击按钮,我都会循环播放音乐!我只需要播放一次并停止!怎么办呢?
谢谢!
答案 0 :(得分:2)
您正在使用m.setLooping(true);
将其设置为循环,将其更改为false
答案 1 :(得分:0)
试试这段代码
try {
Uri mp3 = Uri.parse("url");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(context, mp3);
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(onCompletionListener);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// onCompletionListerner
private OnCompletionListener onCompletionListener = new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mediaPlayer.release();
mediaPlayer = null;
}
};