gpt4 book ai didi

java - Android MediaPlayer::问题

转载 作者:行者123 更新时间:2023-12-01 09:31:56 26 4
gpt4 key购买 nike

我知道这是一个非常常见的问题。但是,尽管我的逻辑是正确的,但我在使用 MediaPlayer 类在我的应用程序中播放声音时遇到了问题。目前,我的应用程序中有震动检测功能。每次摇动设备时,它都应该发出声音。下面是我的代码:

public class MainActivity extends AppCompatActivity {

private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeDetector mShakeDetector;
private SoundManager mSoundManager;
private TextView xText;
private Context context;
private AudioPool ap;
int id1,id2;
File directory;

MediaPlayer player, mPlayer;
AudioCollective ac;
Lagu la;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

xText = (TextView)findViewById(R.id.xText);

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector();

la = new Lagu();
la.initLagu(MainActivity.this);

mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() {

@Override
public void onShake(int count) {

la.playLagu();
xText.setText("Shake:"+count);

}
});
}

public class Lagu {
MediaPlayer mPlayer;
public Lagu(){
mPlayer = new MediaPlayer();
}
public void initLagu(Context theContext){
mPlayer.create(theContext, R.raw.na);
}
public void playLagu(){
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}

}

问题是应用程序在每次手机摇晃时播放声音。应用程序甚至一次都不会播放声音。仅供引用,歌曲的格式是 MP3。有人请告诉我我的应用程序出了什么问题吗?我们将不胜感激您的帮助!

最佳答案

来自documentation对于Mediaplayer.create():

Convenience method to create a MediaPlayer for a given resource id. On success, prepare() will already have been called and must not be called again.

注意:Mediaplayer.create() 方法是一个静态方法,它返回一个现成的 Mediaplayer

所以你需要将返回值分配给你的mPlayer您不需要任何 OnPreparedListener - 只需调用 start()

public class Lagu {

MediaPlayer mPlayer;

public Lagu(){
// do nothing or call initLagu() here
// in this case skip the method call from the Activity's onCreate()
}

public void initLagu(Context theContext){
mPlayer = Mediaplayer.create(theContext, R.raw.na);
}

public void playLagu(){

mPlayer.start();
}

}

关于java - Android MediaPlayer::问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39333919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com