我正在尝试用android studio和Java在我的android手机上做一个游戏。当我把一个音乐文件放到应用程序中时,它会播放,但它只播放了45秒,然后就停止了。我已经在其他几个音乐文件上测试了它,看看它是否以某种方式是音乐文件,但我仍然得到相同的错误。我的目标是让音乐像在游戏中一样循环播放。我已经尝试了各种youtube视频,并查看了其他网站,但我仍然得到相同的问题或无法编译代码。
package com.example.androidstudio2dgamedevelopment;
import static android.media.MediaPlayer.*;
import android.animation.Animator;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.media.MediaPlayer;
import android.view.WindowManager;
import java.util.Vector;
/**
* Main Activity is the entry point to our application
*/
public class MainActivity extends Activity {
private int width;
private int height;
MediaPlayer bkgrdmsc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MediaPlayer mediaPlayer = create(this, R.raw.fg);
mediaPlayer.setLooping(true);
mediaPlayer.start();
//Set Window to fullscreen (will hide status bar)
Window window = getWindow();
this.width = (240);
this.height = (240);
//Set Content view to game, so that objects in the Game Class can be rendered to the screen
setContentView(new Game(this));
}
}
发布于 2021-08-18 04:18:33
我知道是什么了。下面是我使用的代码,它对我很有效。我往往无法找到我的问题的答案,直到我问他们。
package com.example.androidstudio2dgamedevelopment;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Window;
/**
* Main Activity is the entry point to our application
*/
public class MainActivity extends Activity {
private int width;
private int height;
MediaPlayer mysong;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mysong = MediaPlayer.create(MainActivity.this, R.raw.bc);
mysong.start();
mysong.setLooping(true);
//Set Window to fullscreen (will hide status bar)
Window window = getWindow();
this.width = (240);
this.height = (240);
//Set Content view to game, so that objects in the Game Class can be rendered to the screen
setContentView(new Game(this));
}
@Override
protected void onPause() {
super.onPause();
mysong.release();
finish();
}
}
这是我认为我做错了的地方。
我使用MediaPlayer
而不是mysong
作为变量,这似乎对我很有效。在我发布的代码中,我还忘记在this
之前添加MainActivity
。
mysong = MediaPlayer.create(MainActivity.this, R.raw.bc);
mysong.start();
mysong.setLooping(true);
我还在最后添加了这个。
@Override
protected void onPause() {
super.onPause();
mysong.release();
finish();
}
发布于 2021-08-16 03:52:52
只需为媒体播放器添加setLooping(true)即可。
Uri uri = createUri(context, R.raw.fg);
Mediaplayer mediaPlayer= new MediaPlayer();
mediaPlayer.setDataSource(context, uri);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepare();
mediaPlayer.setLooping(true);
mediaPlayer.start();
https://stackoverflow.com/questions/68797146
复制相似问题