我使用asyncTask完成了以下代码,用于在活动背景中运行音乐。
public class BackgroundSound extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... params)
{ MediaPlayer player = MediaPlayer.create(BiographyActivity.this, R.raw.test_cbr);
player.setLooping(true); // Set looping
player.setVolume(100,100);
player.start();
return null; }
}
@Override
protected void onResume()
{ super.onResume();
mBackgroundSound.execute(null); }
@Override
protected void onPause()
{ super.onPause();
mBackgroundSound.cancel(true); }
但它在onResume:
中的执行方法显示错误The method execute(Void[]) is ambiguous for the type BiographyActivity.BackgroundSound
答案 0 :(得分:1)
我强烈建议您不要使用异步任务来播放背景音乐,而是可以使用媒体播放器类中的prepareAsync方法,该方法本身会在后台加载音乐。
以下是我的实施:
import java.io.IOException;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
public class BiographyActivity extends Activity implements OnPreparedListener {
private MediaPlayer mMediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.media_player_activity);
}
@Override
protected void onResume() {
super.onResume();
final AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.test);
try {
releaseMediaPlayer();
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync();
afd.close();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
mMediaPlayer.reset();
mMediaPlayer.release();
}
}
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
}
答案 1 :(得分:0)
这意味着View []不明确,尝试执行(Void [3])或执行();