完美解決Java程式在 MOTO E680i 中音效檔播放

來源:互聯網
上載者:User

這幾天一直在用MOTO SDK來開發一款用於Moto E680i的JAVA遊戲,利用BLOG發表一些心得:

MOTO系列手機中JAVA程式播放一個音效檔比較簡單,但是用於互動式音效時就有問題了。

根據MOTO的一些資料顯示,在MOTO手機中播放聲音有下面幾條約束:

除了同時播放一個MIDI和一個WAV以外,MOTO手機無法同時播放多個聲音,而且必須是先播放MIDI然後播放WAV;

除了MIDI或音階序列以外,不能同時實現player的多個執行個體進入prefetched狀態(預讀取聲音流);

播放新的聲音之前,前一個player必須停止並釋放資源(stop();deallocate())。

如果你遇到以下問題,可以試試我的解決方案:

1)只能播一次,或幾次,接著就無法發出聲音;

2)播放新的聲音時,總是會多播放一次前一個聲音;

3)或者其他奇怪的問題。

My Code:

//引用以下
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;

//定義多個聲效及音效檔的類型
 private String[] arrSoundFile = {"start.mid","right.wav","wrong.wav","help.wav","end.wav"};
 private String[] arrSoundType = {"audio/x-midi","audio/x-wav","audio/x-wav","audio/x-wav","audio/x-wav"};

//定義播放器執行個體
 public Player player;

//定義一個變數,控制是否發聲
  public boolean isSoundOpen = false;

//播放聲音主過程,參數為前面定義的聲音數組的索引號
  public void playMedia(int iKey) throws Exception {

    // 建立執行個體
    player = Manager.createPlayer(
        getClass().getResourceAsStream("/midi/"+arrSoundFile[iKey]), arrSoundType[iKey]);

    // 綁定狀態更新事件程序
    player.addPlayerListener(this);

    //播放聲音
    player.setLoopCount(1); 
    player.prefetch(); // prefetch
    player.realize(); // realize
    player.start(); // and start
  }

// 播放器狀態更新事件程序
 public void playerUpdate(Player player, String event, Object eventData) {

    //調試 跟蹤過程
    //    System.err.println("event:" + event);

    //如果播放結束,就釋放和關閉播放器執行個體
    if (event.equals("endOfMedia")) {
    player.deallocate();
    player.close();
    }
}

//播放聲音調用過程
 public void playSound(int iKey) {
   if(isSoundOpen)
  {
       try {
          playMedia(iKey);
        } catch (Exception e) {
          System.err.println("Unable to play: " + e);
          e.printStackTrace();
        }
      }
}

/*
歡迎轉載,請保留以下著作權說明
========================
  風雨雷電堂在學J2ME
========================
不保留以上著作權說,說明你很差
*/

大家可以在MOTO的機子上測試。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.