2013-07-28 96 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