我想在一個普通的類裏面使用MediaPlayer類播放mp3音效,這意味着非Activity。我的問題可能是初始化MediaPlayer對象,因爲我在非Activity類中沒有Context。這是如何解決的?Android的mp3交叉類
謝謝!
編輯
這裏是從哪裏函數應該叫一些代碼:
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初始化的Activity,它試圖從這裏開始它。
下面是活動代碼:
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();
}
}
主要的Android entrypoits活動,服務的構造,廣播接收器有一個語境。如果其中一個創建/啓動播放器,則可以將@mac建議的上下文傳遞給該播放器。或者你有什麼特別的? – k3b 2012-04-21 15:24:14
@ k3b我有一些特別的東西,我的媒體播放器沒有被任何這些調用,所以我沒有上下文。任何解決方案? – arielschon12 2012-04-21 15:27:36
請把你從一些代碼調用java類... – MAC 2012-04-21 15:35:34