2014-12-30 2 views
0

С помощью этой части кода я смог запустить песню в фоновом режиме, нажав кнопку «Да», и остановить ее «нет», но она работает только один раз. Если я снова нажму кнопку «Да» (второй раз), приложение остановится. Так что нужна помощь, я хочу, чтобы моя моя деятельность запускалась и останавливала музыку с помощью этих кнопок диалога оповещения при каждом нажатии.Android-плеер не работает во второй раз

public class Music extends Activity { 

final Context context = this; 
MediaPlayer song; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.menu); 

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
      context); 

    alertDialogBuilder 
      .setMessage("Turn ON the music?") 
      .setCancelable(false) 
      .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 

        song.setAudioStreamType(AudioManager.STREAM_MUSIC); 
        try { 
         song = MediaPlayer.create(Music.this, R.raw.fing); 
        } catch (IllegalArgumentException e) { 
         Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
        } catch (SecurityException e) { 
         Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
        } catch (IllegalStateException e) { 
         Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
        } 
        try { 
         song.prepare(); 
        } catch (IllegalStateException e) { 
         Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
        } catch (IOException e) { 
         Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
        } 
        song.start(); 
       } 


       // dialog.cancel(); 
      } 


       ) 


       .setNegativeButton("No",new DialogInterface.OnClickListener() { 
        public void onClick (DialogInterface dialog,int id){ 
         // if this button is clicked, just close 
         // the dialog box and do nothing 
         if(song!=null && song.isPlaying()){ 
          song.stop(); 
          dialog.cancel(); 

         } 
        }}); 

       // create alert dialog 
       AlertDialog alertDialog = alertDialogBuilder.create(); 

       // show it 
       alertDialog.show();}} 
+0

попробуйте назначить и установить аудио 'MediaPlayer song' в' onCreate', в 'PositiveButton' просто' song.start(); ' – waki

+0

@Waki Я попробовал сначала, он работает, но только один раз; Если я нажму «yes'_first time_», песня будет воспроизводиться, и если я нажму «no'_first time_», она остановится, и когда я снова нажму «да» _ секунд второго раза, приложение остановится. Поэтому я использовал try/catch, но это не сработало. – Journey

+0

вы меня не понимаете, 'setAudioStreamType',' MediaPlayer.create' и 'prepare' также помещены в' onCreate', в 'PositiveButton'' onClick' просто' song.start(); ' – waki

ответ

1

Вся инициализация медиаплеер (например, создание, setAudioStreamType, подготовить) экземпляр можно поместить в методе OnCreate не OnClick диалога. И в onClick просто вызовите методы остановки и воспроизведения.

Как это

public class Music extends Activity { 

    final Context context = this; 
    MediaPlayer song; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.menu); 

    song.setAudioStreamType(AudioManager.STREAM_MUSIC); 
         try { 
          song = MediaPlayer.create(Music.this, R.raw.fing); 
         } catch (IllegalArgumentException e) { 
          Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
         } catch (SecurityException e) { 
          Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
         } catch (IllegalStateException e) { 
          Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
         } 
         try { 
          song.prepare(); 
         } catch (IllegalStateException e) { 
          Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
         } catch (IOException e) { 
          Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
         } 

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
      context); 

    alertDialogBuilder 
      .setMessage("Turn ON the music?") 
      .setCancelable(false) 
      .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        song.start(); 
       } 


       // dialog.cancel(); 
      } 


       ) 


       .setNegativeButton("No",new DialogInterface.OnClickListener() { 
        public void onClick (DialogInterface dialog,int id){ 
         // if this button is clicked, just close 
         // the dialog box and do nothing 
         if(song!=null && song.isPlaying()){ 
          song.stop(); 
          dialog.cancel(); 

         } 
        }}); 

       // create alert dialog 
       AlertDialog alertDialog = alertDialogBuilder.create(); 

       // show it 
       alertDialog.show(); 
    } 
} 
+0

Не против друзей, но никто из них не работал. Я думаю, мне нужно использовать поток, чтобы решить эту проблему. – Journey

1

Используйте этот

.setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int id) { 
song.reset(); // this makes sure that the song object was not assigned before (it recreates the MediaPlayer) 
        song.setAudioStreamType(AudioManager.STREAM_MUSIC); 
        try { 
         song = MediaPlayer.create(Music.this, R.raw.fing); 
        } catch (IllegalArgumentException e) { 
         Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
        } catch (SecurityException e) { 
         Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
        } catch (IllegalStateException e) { 
         Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
        } 
        try { 
         song.prepare(); 
        } catch (IllegalStateException e) { 
         Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
        } catch (IOException e) { 
         Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
        } 
        song.start(); 
       } 


      // dialog.cancel(); 
     } 


      ) 

.setNegativeButton("No",new DialogInterface.OnClickListener() { 
       public void onClick (DialogInterface dialog,int id){ 
        // if this button is clicked, just close 
        // the dialog box and do nothing 
        if(song!=null && song.isPlaying()){ 
         song.stop(); 
song.release(); // This releases the song object so you can initiate another MediaPlayer object if you want. 
         dialog.cancel(); 

        } 
       }}); 

Это сбрасывает объект MediaPlayer, чтобы убедиться, что у вас есть свежие один, и если музыка перестает играть он освобождает MediaPlayer (который также выпускает память RAM)

0

Try позвонить

if (song !=null){ 
song.release()} 

перед тем

song = MediaPlayer.create(Music.this, R.raw.fing); 

Можете ли вы показать журналы?

0

Я решаю эту проблему при вызове song.start() внутри setOnPreparedListener, любой вызов для запуска вне этого метода создает ошибку.

Смежные вопросы