以下播放约30次,然后停止播放音频。 (程序继续运行。)我已经读过,我可能会创建太多的播放器实例。如何修改此代码以防止这种情况? (此代码已使用建议进行编辑,但仍然只播放约30次。)
public static MediaPlayer m;
private void playboopboop(String fileName) {
try {
AssetFileDescriptor d = getAssets().openFd(fileName);
long start = d.getStartOffset();
long end = d.getLength();
this.m = new MediaPlayer();
this.m.setDataSource(d.getFileDescriptor(), start, end);
this.m.setLooping(false);
this.m.prepare();
this.m.start();
} catch (Exception e) {
doalert("Audio Error: " + e);
}
}
答案 0 :(得分:0)
在函数外部创建媒体播放器,并将其作为变量传递给函数,或者如果您在类中,则引用它。这将帮助您不小心创建太多实例。您还应该将循环设置为false。如果循环为真,那么一旦文件完成,它将再次启动。例如:
private void playboopboop(String fileName, MediaPlayer m) {
try {
AssetFileDescriptor d = getAssets().openFd(fileName);
long start = d.getStartOffset();
long end = d.getLength();
m.setDataSource(d.getFileDescriptor(), start, end);
m.setLooping(false);
m.prepare();
m.start();
} catch (Exception e) {
doalert("Audio Error: " + e);
}
}
或者像这样:
//Defined in the class you are using
public MediaPlayer m = new MediaPlayer();
private void playboopboop(String fileName) {
try {
AssetFileDescriptor d = getAssets().openFd(fileName);
long start = d.getStartOffset();
long end = d.getLength();
this.m.setDataSource(d.getFileDescriptor(), start, end);
this.m.setLooping(false);
this.m.prepare();
this.m.start();
} catch (Exception e) {
doalert("Audio Error: " + e);
}
}
答案 1 :(得分:0)
reset方法将停止任何媒体并将MediaPlayer实例发送回处于空闲状态,处于创建时的相同状态。工作代码如下:
public MediaPlayer m = new MediaPlayer();
private void playboopboop(String fileName) {
try {
AssetFileDescriptor d = getAssets().openFd(fileName);
long start = d.getStartOffset();
long end = d.getLength();
m.reset(); // set player to initial creation state
m.setDataSource(d.getFileDescriptor(), start, end);
m.prepare();
m.start();
} catch (Exception e) {
doalert("Audio Error: " + e);
}
}