Android MediaPlayer 减慢了代码流
Android MediaPlayer slows down the code flow
我正在尝试为游戏创建音效。
但是当音效开始播放时使用 MediaPlayer - 游戏速度会减慢一秒钟。
如果我使用大量音效 - 游戏真的很挣扎。
我想我的认识有问题。
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// ...
if(somethingHappened) {
final MediaPlayer mySound = MediaPlayer.create(getContext(), R.raw.sound1);
mySound.start();
//...
}
//...
}
使用短 mp3 文件
尝试清理 mySound:
public class MyService extends Service {
MediaPlayer mySound;
// ...
@Override
public void onDestroy() {
if (mySound != null) mySound.release();
}
}
更多详情:http://developer.android.com/guide/topics/media/mediaplayer.html
希望对您有所帮助!
最好将媒体播放器声明为一个字段,并且只在 onCreate() 中而不是在 onDraw() 中创建一次。现在,每次调用 onDraw() 时(通常调用次数很多),您都会创建一个新的媒体播放器,它会占用资源。
如果不需要它,也可以做 mySound.pause(),就像 Mounir 说 mySound.release() 当你想杀死它时。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
final MediaPlayer mySound = MediaPlayer.create(getContext(),R.raw.sound1);
...
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(somethingHappened) {
mySound.start();
// might also want to call mySound.stop() at some point too
}
protected void onPause(){
super.onPause();
mySound.pause();
}
protected void onDestroy(){
super.onDestroy();
mySound.release();
}
我正在尝试为游戏创建音效。 但是当音效开始播放时使用 MediaPlayer - 游戏速度会减慢一秒钟。 如果我使用大量音效 - 游戏真的很挣扎。 我想我的认识有问题。
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// ...
if(somethingHappened) {
final MediaPlayer mySound = MediaPlayer.create(getContext(), R.raw.sound1);
mySound.start();
//...
}
//...
}
使用短 mp3 文件
尝试清理 mySound:
public class MyService extends Service {
MediaPlayer mySound;
// ...
@Override
public void onDestroy() {
if (mySound != null) mySound.release();
}
}
更多详情:http://developer.android.com/guide/topics/media/mediaplayer.html
希望对您有所帮助!
最好将媒体播放器声明为一个字段,并且只在 onCreate() 中而不是在 onDraw() 中创建一次。现在,每次调用 onDraw() 时(通常调用次数很多),您都会创建一个新的媒体播放器,它会占用资源。 如果不需要它,也可以做 mySound.pause(),就像 Mounir 说 mySound.release() 当你想杀死它时。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
final MediaPlayer mySound = MediaPlayer.create(getContext(),R.raw.sound1);
...
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(somethingHappened) {
mySound.start();
// might also want to call mySound.stop() at some point too
}
protected void onPause(){
super.onPause();
mySound.pause();
}
protected void onDestroy(){
super.onDestroy();
mySound.release();
}