活动的背景音频

时间:2016-03-18 13:48:09

标签: java android audio

我想在我正在解释示例的活动的背景中添加我录制的音频。问题是音频在结束活动后不会停止并继续播放。我希望只在我的活动在前面时播放音频。请将服务类放在以下代码中

public class exp extends Activity  {
    ImageView imview1,imview2;
    final MediaPlayer mediaPlayer=new MediaPlayer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addexample);


        imview2 = (ImageView) findViewById(R.id.imageView2);
        mediaPlayer.create(exp.this,R.raw.babydoll);

        imview2.setVisibility(View.INVISIBLE);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                imview2.setVisibility(View.VISIBLE);
                mediaPlayer.start();
                mediaPlayer.setLooping(true);
                mediaPlayer.setVolume(100,100);

            }
        }, 2000);




    }
    protected void onPause(){
        super.onPause();
        mediaPlayer.pause();
    }

}

1 个答案:

答案 0 :(得分:1)

首先。您必须使用服务播放音乐,但如果您不想使用服务。实现媒体播放器的方式是mediaPlayer = MediaPlayer.create(this,R.raw.facebook_tone);.

此代码当活动传递到后台时音乐暂停,当活动传递到前台时音乐继续播放。

public class MainActivity extends AppCompatActivity {

MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //get the MediaPlayer object
    mediaPlayer = MediaPlayer.create(this,R.raw.facebook_tone);

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {

            mediaPlayer.start();
            mediaPlayer.setLooping(true);
            mediaPlayer.setVolume(100,100);

        }
    }, 2000);
}

@Override
protected void onPause() {
    super.onPause();
    //pause the music
    mediaPlayer.pause();
}

@Override
protected void onResume() {
    super.onResume();
    //validate if the mediaplayer is not null and not playing
    if(mediaPlayer != null && !mediaPlayer.isPlaying()){

        mediaPlayer.start();

    }
}

}