通常のクラス内で MediaPlayer クラスを使用して mp3 サウンドを再生しようとしています。つまり、Activity ではありません。Activity 以外のクラスに Context がないため、私の問題はおそらく MediaPlayer オブジェクトの初期化です。これはどのように解決できますか?
ありがとう!
編集
関数を呼び出す必要がある場所からのコードを次に示します。
public class Bullet extends Thread{
public int bx = SniperActivity.bulletx;
public int by = SniperActivity.bullety;
Player obj = new Player();
SniperActivity con = new SniperActivity();
public void shoot(){
if (bx == Place.spotx && by == Place.spoty)
{
for (int f = 0; f<Rifle.dam; f++)
{
Player.life--;
if(Player.life<=0){
obj.death();
}
try {
Bullet.sleep(Rifle.rate);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
int s = 0;
s++;
while (s == Rifle.magazine)
{
try {
Bullet.sleep(Rifle.relode);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
s = 0;
}
con.Mplayer.start();
}
}
この関数は、この「con.Mplayer.start()」行で、shoot() 関数から呼び出されます。con オブジェクトは、Mplayer が初期化されているアクティビティを参照しており、ここから開始しようとしています。
アクティビティ コードは次のとおりです。
public class SniperActivity extends Activity{
private GameView game;
private Player player;
private Scop scope;
public static int scopx;
public static int scopy;
public static int bulletx;
public static int bullety;
public static String filename = "SharedData";
static SharedPreferences someData;
public static int Width;
public static int Height;
public MediaPlayer Mplayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Mplayer = MediaPlayer.create(SniperActivity.this, R.raw.shot);
someData = getSharedPreferences(filename, 0);
Height = someData.getInt("height", 480);
Width = someData.getInt("width", 480);
scopx = 1;
scopy = 1;
PlayerView playerview;
playerview = new PlayerView(this, player);
ScopView Scope;
Scope = new ScopView(this, scope);
this.game = new GameView(this);
game.setviews(playerview, Scope);
setContentView(game);
int screenWidth,screenHeight;
screenWidth = this.getWindowManager().getDefaultDisplay().getWidth();
screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
bulletx = screenWidth/2;
bullety = screenHeight/2;
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
float dx;
Bullet bullet = new Bullet();
//get the x coordinate of users' press
dx = event.getX();
if (dx >=0)
{
bullet.shoot();
}
return true;
}
public void onDeath(){
finish();
}
}