当用户重新开始活动时再次播放声音

时间:2014-05-22 13:52:13

标签: android media-player audio

我所拥有的是一种活动,每当用户打开它时我会播放一些声音,但当他到达它的儿童活动时...它会停止,因为我想...但我想要用户按下按钮时返回此活动(这是父活动)再次播放此声音...我该怎么做...这是我的一些代码:

 public class GeneralScreen extends Activity {
    String mytext="";
    MediaPlayer mMediaPlayer;
    protected static final int RESULT_SPEECH = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.general_screen);


        GridView g = (GridView) findViewById(R.id.myGrid);
         mMediaPlayer = new MediaPlayer();
        mMediaPlayer = MediaPlayer.create(this, R.raw.selecteng);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setLooping(false);
        mMediaPlayer.start();

        mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

            public void onCompletion(MediaPlayer mp) {

                Log.i("Completion Listener","Song Complete");
                Toast.makeText(GeneralScreen.this, "Media Completed", Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);  //for open google API
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");     //for transfer voice from google API to text in EditText

                try {
                    startActivityForResult(intent, RESULT_SPEECH);  // for get result


                } catch (ActivityNotFoundException a) {
                    Toast t = Toast.makeText(getApplicationContext(),   //if make error get this message
                            "Ops! Your device doesn't support Speech to Text",
                            Toast.LENGTH_SHORT);
                    t.show();
                }
            }
        });

3 个答案:

答案 0 :(得分:0)

您只需使用以下方法@Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); //play music code here } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); //stop music code here }

答案 1 :(得分:0)

你需要在适当的生命周期方法中执行你的playSound()方法(在这种情况下,我认为它可能是onResume())。

了解活动生命周期是非常基础的,并且理解很重要,请查看以下资源以获取更多信息: http://developer.android.com/training/basics/activity-lifecycle/index.html

答案 2 :(得分:0)

只需创建一个方法playYourMusic()并将所有代码放入内部启动mediaplayer。然后将playYourMusic放入onRestart和onCreate():

    @Override
   protected void onRestart() {

    playYourMusic();

     super.onRestart();


   }

想一想,当你回到主要时,完成你要离开的活动。那么,为什么不在onResume()?因为onResume()也是在Activity的开头调用的。有些设备以不同的方式处理android的LifeCycle。