2013-07-28 94 views
0

我可以在我的活動中播放聲音。例如:Android - 在類文件中播放聲音?

public class APP extends Activity { 

MediaPlayer btnClick; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 

btnClick = MediaPlayer.create(this, R.raw.button_click); 

    } 

... on Button Click play sound ... 
btnClick.start(); 
... 

} 

但我不知道如何在類文件中播放聲音?

public class test { 
... 
} 

這不可能嗎?我嘗試了很多變化。在課堂文件中,我無法播放聲音。

回答

1

您必須將您的Context轉發給構造函數中的類。

添加類成員爲您Context

Context mContext; 

然後,添加一個構造函數,一個Context

Test test = new Test(this); //Assuming you call this in an Activity 

public test (Context c){ 
    mContext = c; 
} 

使用此構造實例化類最後,你想在你的課堂上發揮你的聲音,使用mContext作爲Context

MediaPlayer mp = MediaPlayer.create(mContext, R.raw.button_click); 

如果你想實例化一個的FrameLayout類,使用此代碼:

Test test = new Test(getContext()); //Assuming you call this in a subclass of FrameLayout 
+0

這不起作用。 – Johnny

+0

什麼是不工作? –

+0

當我嘗試使用這個:Test test = new Test(this); - >該應用程序崩潰 – Johnny

1

只能在測試類指定媒體播放器,然後調用從測試方法涉及mediaPlayerSettings的類。測試類本身無法播放,因爲它不會擴展活動。

但是,如果你想從類測試方法那樣做:

public class test 
{ 

private static MediaPlayer mp; 

public static void startPlayingSound(Context con) 
{ 
mp= MediaPlayer.create(con, R.raw.sound); 
mp.start(); 
} 

//and to stop it use this method below 

public static void stopPlayingSound(context con) 
{ 
if(!mp.isPlaying()) 
{ 
mp.release(); 
mp = null; 
} 
} 

} 

因此在活動調用它像:

//for start 
test.startPlayingSound(this); 
//and for stop 
test.stopPlayingSound(this); 

希望它會幫助你。

+0

我想在類文件中調用它。我認爲問題在這裏,我不會延長活動。那就是你說的。 – Johnny

+0

如果你想在測試類文件中調用它,那麼測試類必須擴展活動。 – Helmisek

+0

我在我的課FrameLayout擴展。我可以給兩件事:擴展FrameLayout,活動? – Johnny