android中暫停背景音樂_Android

來源:互聯網
上載者:User

網上有很多暫停背景音樂的例子,最多的就是根據暫停指令去發廣播來暫停音樂。其實這種方式很不靠譜,為什嗎?因為其他的播放器不一定註冊監聽了那個廣播,所以大多數情況是不起作用的。

下面有一種比較靠譜的方式,是通過觸發媒體的按鈕來操作播放器狀態。

複製代碼 代碼如下:

sendMediaButton(context,<span style="font-size:9pt;line-height:1.5;color:#2B91AF;">KeyEvent</span><span style="font-size:9pt;line-height:1.5;">.KEYCODE_MEDIA_PAUSE);</span>

複製代碼 代碼如下:

private static void sendMediaButton(Context context, int keyCode) {
    KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
    Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
    context.sendOrderedBroadcast(intent,null);
 
    keyEvent = new KeyEvent(KeyEvent.ACTION_UP, keyCode);
    intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
    context.sendOrderedBroadcast(intent,null);
}

網友實現的另一種方法

簡約寫下流程

{ private Visualizer visualizer = null;//頻譜測試器 private byte [] mRawVizData;//頻譜容器 //執行個體化 Visualizer 對象 visualizer = new Visualizer(0);  mRawVizData = new byte[128]; //對象的初始化 if(visualizer != null) {  if (visualizer.getEnabled()) {    visualizer.setEnabled(false);   }    visualizer.setCaptureSize(mRawVizData.length);//一定要在頻譜false狀態使用    visualizer.setEnabled(true);//開啟頻譜擷取 }

下面是開一個線程進行迴圈擷取頻譜資訊,我只把擷取給貼出來

int status = Visualizer.ERROR; if(visualizer != null) {  //音樂頻譜擷取  status = visualizer.getFft(mRawVizData);//擷取波形圖  if(status != Visualizer.SUCCESS)  {  Log.i("answer", "getWaveFail");  }  else  {               int j = 0;  for(int i = 0; i < 128; i++)  {    if(mRawVizData[i] == 0)    {      j++;    }  }    Log.i("answer", "getWave j = " + j);  } }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.