Android:媒体播放器创建
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12154951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android: mediaplayer create
提问by cyclingIsBetter
I have this code:
我有这个代码:
package com.example.pr;
import android.media.MediaPlayer;
public class Audio{
MediaPlayer mp;
public void playClick(){
mp = MediaPlayer.create(Audio.this, R.raw.click);
mp.start();
}
}
I have an error in "create" with this message "The method create(Context, int) in the type MediaPlayer is not applicable for the arguments (Audio, int)"
我在“创建”中有一条错误消息“MediaPlayer 类型中的方法 create(Context, int) 不适用于参数 (Audio, int)”
why?
为什么?
回答by P.Melch
MediaPlayer.create() needs a Contextas first parameter. Pass in the current Activityand it should work.
MediaPlayer.create() 需要一个Context作为第一个参数。传入当前活动,它应该可以工作。
try:
尝试:
public void playClick(Context context){
mp = MediaPlayer.create(context, R.raw.click);
mp.start();
}
in your Activity:
在您的活动中:
audio = new Audio();
...
audio.playClick(this);
but don't forget to call release on the MediaPlayer instance once the sound has finished, or you'll get an exception.
但是不要忘记在声音完成后在 MediaPlayer 实例上调用 release ,否则你会得到一个异常。
However, for playing short clicks using a SoundPoolmight be better anyway.
但是,无论如何,使用SoundPool播放短点击可能会更好。
回答by Alexis C.
public class Audio{
MediaPlayer mp;
Context context;
public Audio(Context ct){
this.context = ct;
}
public void playClick(){
mp = MediaPlayer.create(context, R.raw.click);
mp.prepare();
mp.start();
}
From your Activity:
从您的活动:
Audio audio = new Audio(YourActivity.getApplicationContext());
audio.playClick();