2016-07-08 98 views
0

背景音乐,我很新的Android和尝试添加使用下面的代码背景音乐:如何停止按钮然后在Android

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     MediaPlayer player; 
     AssetFileDescriptor afd; 
     try { 
      afd = getAssets().openFd("bg.mp3"); 
      player = new MediaPlayer(); 
      player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),afd.getLength()); 
      player.setLooping(true); 
      player.prepare(); 
      player.start(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     setContentView(R.layout.activity_main); 
    } 

和现在的背景音乐运行良好。但我想通过点击图像按钮来停止背景音乐。但我没有得到任何想法如何做到这一点。然而我已经尝试了下面但根本不工作:

protected void stopmus(View view) { 
     MediaPlayer player; 
      player = new MediaPlayer(); 
      super.onStop(); 
      player.stop(); 
      player = null; 

    } 

请帮我解决它。

+1

变化的媒体播放器实例var和不与本地范围。当前你正在创建一个新的对象并且在其上调用stop ...这不会阻止播放该轨道的原始MediaPlayer对象。 – Shubhank

+1

是'onCreate'&'stopmus'谎言在同一类? –

+1

尝试将Mediaplayer播放器指定为字段变量。这意味着全局变量..在oncreate()之前。然后onCreate()初始化这个变量 - > player = new Mediaplayer();播放音乐,并停止不分配一个新的媒体播放器..just player.stop(); –

回答

0

Make MedaiPlayer 一个全局变量声明方onCreate()

MediaPlayer player; 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    // YOUR CODE 
} 

变化YOUT停止方法是这样的:

protected void stopmus(View view) { 

     if(player!=null) 
     { 
      player.stop(); 
      player = null; 
     } 
     super.onStop(); 
} 
+0

嗨,它按预期工作。但在某些移动设备上(Android版本5),当我点击停止音乐按钮时,该应用突然退出,没有任何错误。 –

+0

在logcat中可能有些东西。尝试找出2-3次或重新启动Android Studio。 –

+0

我得到这些日志:http://pastebin.com/YcAAC17f –