gpt4 book ai didi

java - Android MediaPlayer 运行时错误

转载 作者:行者123 更新时间:2023-12-01 14:16:58 24 4
gpt4 key购买 nike

使用这段代码我想播放声音。我为其调用 playSound() 方法

public class MainActivity extends Activity
{
private MediaPlayer cPiano;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(new GameView(this));
}
public void playSound(){
cPiano = MediaPlayer.create(this, R.raw.cpiano);
cPiano.start();
}
}
<小时/>
public class GameView extends SurfaceView
{
private SurfaceHolder surfaceHolder;
private MainActivity mainActivity

public GameView(Context context)
{
super(context);
mainActivity = new MainActivity();
}

@Override
protected void onDraw(Canvas canvas)
{
for (Pixel pixel : pixelList)
{
pixel.onDraw(canvas);
}
for (int i = pixelList.size() - 1; i >= 0; i--)
{
Pixel pixel = pixelList.get(i);
if (pixel.isBar())
{
mainActivity.playSound();
removePixel(i);
break;
}
}
}

这只是最重要的代码。但是当它应该播放声音时我收到 Android 运行时错误

出了什么问题?

最佳答案

代替 mainActivity.playSound() 行尝试:

MainActivity host = (MainActivity)getContext();
host.playSound();

同时删除新的 MainActivity()。 Activity 不得直接实例化

关于java - Android MediaPlayer 运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18046843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com