概述
放寒假了,有點暈車,因此多休息了一天,
今天繼續構建 Miwok 語言應用,之前在 安卓學習日志 — Day05 中已經測驗過了音頻播放的功能,那么接下來就為Miwok 應用的每個類別添加上 單詞的發音,
還是老樣子,先做一個頁面的(如:NumbersActivity) ,確保功能正常后 ,才按照同樣的方法來更改其他的頁面,
目標
- 為每個單詞添加音頻
- 點擊某一單詞時,立即正在播放的音頻,而去播放被點擊的單詞的音頻,
- 當用戶離開 某一 Activity 的頁面時,立即停止播放
- 與系統或其他應用互動
實作步驟
添加音瞥澩
這之前為每個頁面的單詞添加圖片的方法基本一樣,
更改 Word 類,添加一個成員變數 audioResourceId 用于存盤 音瞥澩的ID,并更改建構式以接收音瞥澩ID,
**值得注意的是 ,**需要同時更改兩個建構式:
一個接收 圖片資源ID,而另一個不接收(Phrases頁面沒有圖片,而另外 3個 頁面有圖片)
/**
* Create a new Word object.
*
* @param defaultTranslation is the word in a language that the user is already familiar with
* (such as English)
* @param miwokTranslation is the word in the Miwok language
* @param audioResourceId is the audio resource id with the word
*/
public Word(String defaultTranslation, String miwokTranslation, int audioResourceId) {
this.defaultTranslation = defaultTranslation;
this.miwokTranslation = miwokTranslation;
this.audioResourceId = audioResourceId;
}
/**
* Create a new Word object.
*
* @param defaultTranslation is the word in a language that the user is already familiar with
* (such as English)
* @param miwokTranslation is the word in the Miwok language
* @param imageResourceId is the drawable resource ID for the image associated with the word
* @param audioResourceId is the audio resource id with the word
*/
public Word(String defaultTranslation, String miwokTranslation, int imageResourceId, int audioResourceId) {
this.defaultTranslation = defaultTranslation;
this.miwokTranslation = miwokTranslation;
this.imageResourceId = imageResourceId;
this.audioResourceId = audioResourceId;
}
然后將 所有單詞的音頻檔案放在 res/raw 目錄下,并更改 每個 Activity 中的資料源,為每個 Word 物件 添加 音瞥澩ID:

播放完成自動清空
當一個音頻播放完成時應該 釋放其占用的資源,為系統及其他應用的運行提供保障,
MediaPlayer 類的 可以系結一個 OnCompletionListener 監聽器,該監聽器會在音頻播放完成時回呼 onCompletion 方法,因此播放完成時釋放資源的邏輯就該寫在 OnCompletionListener 監聽器的 onCompletion 方法當中,
在 NumbersActivity 中自定義一個輔助方法 releaseMediaPlayer,用于釋放 MedaiPlayer 所占用的資源:
/**
* Clean up the media player by releasing its resources.
*/
private void releaseMediaPlayer() {
// If the media player is not null, then it may be currently playing a sound.
if (mediaPlayer != null) {
// Regardless of the current state of the media player, release its resources
// because we no longer need it.
mediaPlayer.release();
// Set the media player back to null. For our code, we've decided that
// setting the media player to null is an easy way to tell that the media player
// is not configured to play an audio file at the moment.
mediaPlayer = null;
}
}
}
為 NumbersActivity 注冊一個全域的 OnCompletionListener 監聽器物件,并在 onCompletion 方法中呼叫剛剛自定義的輔助方法:
/**
* This listener gets triggered when the {@link MediaPlayer} has completed
* playing the audio file.
*/
private MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
releaseMediaPlayer();
Toast.makeText(NumbersActivity.this, "released.", Toast.LENGTH_SHORT).show();
}
};
最后只需使單擊每個單詞時,播放對應的音瞥澩即可,這使用到了 AdapterView.OnItemClickListener 監聽器,因為 ListView 繼承自 AdapterView ,當 ListView 中的任一串列項被點擊時,都會回呼 OnItemClickListener 監聽器的 onItemClick 方法,因此 點擊 單詞并播放音頻的邏輯代碼應寫在該方法當中,
下面為 ListView 根視圖系結一個 OnItemClickListener:
**提示: ** 僅在呼叫 mediaPlayer.start() 方法之后再設定該回呼,否則將無法觸發該回呼,
// Set a click listener to play the audio when the list item is clicked on
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get the {@link Word} object at the given position the user clicked on
Word clickedWord = adapter.getItem(position);
Toast.makeText(NumbersActivity.this, String.format("item %d clicked.", position), Toast.LENGTH_SHORT).show();
// Create and setup the {@link MediaPlayer} for the audio resource associated with the current word
mediaPlayer = MediaPlayer.create(NumbersActivity.this, clickedWord.getAudioResourceId());
// Start the audio file
mediaPlayer.start(); // no need to call prepare(); create() does that for you
// Setup a listener on the media player, so that we can stop and release the
// media player once the sound has finished playing.
mediaPlayer.setOnCompletionListener(completionListener);
}
});
這時候,在 Numbers 頁面中單擊任意單詞將播放其音頻,并在播放完成時自動釋放到音頻播放所使用到的資源,
播放另一音頻
現在 出現了一個問題,如果在一個單詞讀完之前單擊了另一個單詞,這時前一個單詞的音頻會和后一個單詞的音頻出現重疊,
這是因為在點擊第二個單詞時,上一個單詞的音頻 沒有被清空掉,所以仍然繼續播放,
解決方法也很簡單,在單詞任一單詞時,首先釋放之前的資源,然后在播放音頻,因此,更改 onItemClick 方法如下:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Release the media player if it currently exists because we are about to
// play a different sound file
releaseMediaPlayer();
// Get the {@link Word} object at the given position the user clicked on
Word clickedWord = adapter.getItem(position);
Toast.makeText(NumbersActivity.this, String.format("item %d clicked.", position), Toast.LENGTH_SHORT).show();
// Create and setup the {@link MediaPlayer} for the audio resource associated with the current word
mediaPlayer = MediaPlayer.create(NumbersActivity.this, clickedWord.getAudioResourceId());
// Start the audio file
mediaPlayer.start(); // no need to call prepare(); create() does that for you
// Setup a listener on the media player, so that we can stop and release the
// media player once the sound has finished playing.
mediaPlayer.setOnCompletionListener(completionListener);
}
現在,在一個單詞讀完之前單擊了另一個單詞,這時首先清空前一個單詞的資源(即停止播放)然后再播放第二個單詞的音頻,這兩個動作發生在一瞬間,
切換頁面時
我們只希望用戶在 這個 Activity 頁面時能夠播放音頻,一旦離開了這個 Activity 頁面就立即停止正在播放 的音頻,并清空資源,
這就需要涉及到 Activity 的生命周期了,從官方檔案中得知 當一個應用 失去焦點進入停止狀態時,系統會連續得呼叫 onPause() 和 onStop() 方法,
那么 ,只需 在 這兩個方法的任意一個當中釋放 音瞥澩即可,比如在 onStop 方法中:
@Override
protected void onStop() {
super.onStop();
// When the activity is stopped, release the media player resources because we won't
// be playing any more sounds.
releaseMediaPlayer();
Toast.makeText(getApplicationContext(), "Activity stopped.", Toast.LENGTH_SHORT).show();
}
現在,點擊一個單詞播放音頻,在音頻播放結束之前 ,迅速切換到其他的應用當中,音頻將立即結束并釋放資源,
應用互動
要在移動設備上做個良好公民,我們應該思考下,我們的應用該如何與系統及其他也想播放音頻的應用互動,
Android 使用 Audio focus 來管理設備上的音頻播放操作,這意味著任何時候只有掌握 Audio Focus 的應用才能播放音頻,有時候就意味著暫停或播放我們應用中的音頻一邊其他更重要的音頻能播放,
比如,在我們正在聽音樂時,有人打電話過來,這時音樂會自動停止播放,并在通話結束之后自動繼續播放,
Audio Focus 可以通過 Audio Manager 請求獲得,而 Audio Manager 是一項系統服務,系統服務可以為所有應用都提供常見的功能,例如 通知服務 或鬧鐘管理器服務,某些系統服務可以讓我們訪問設備上的硬體組件,例如 位置資訊管理器服務,
但最終,系統服務只是一組 java 類,可以像對待任何其他 Java 類一樣通過獲得物件實體然后對其呼叫方法來進行互動,
Audio Focus 也有屬于自己的狀態:
| Audio Focus State | Description of this state in your own words | Describe what we should do in the Miwok app when we enter this state |
|---|---|---|
| AUDIOFOCUA_GAIN | Gain audio focus back again (after having lost it earlier) | Resume playing the audio file |
| AUDIOFOCUS_LOSS | Permanent loss of audio focus | Stop the MediaPlpayer and release resource |
| AUDIOFOCUS_LOSS_TRANSIENT | Temporary loss of audio focus | Pause audio file |
| AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK | Temporary loss of audio focus, can “duck” or lower volume if applicable | Pause audio file (each part of the word pronunciation is important to be heard) |
我們應該做個良好公民,當 Audio Focus 狀態發生變化時應該調整音頻播放的行為,直接上代碼吧,
首先在 NumbersActivity 中定義一個成員變,顧名思義 這個AudioManager 物件用于管理 Audio Focus:
/**
* Handles audio focus when playing a sound files
**/
private AudioManager audioManager;
一個作用于 Activity 全域的 audioFocusChangeListener :
/**
* This listener gets triggered whenever the audio focus changes
* (i.e., we gain or lose audio focus because of another app or device).
*/
AudioManager.OnAudioFocusChangeListener audioFocusChangeListener =
new AudioManager.OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
// The AUDIOFOCUS_LOSS case means we've lost audio focus and
// Stop playback and clean up resources
releaseMediaPlayer();
Toast.makeText(NumbersActivity.this, "AUDIOFOCUS_LOSS", Toast.LENGTH_SHORT).show();
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
// The AUDIOFOCUS_LOSS_TRANSIENT case means that we've lost audio focus for a
// short amount of time. The AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK case means that
// our app is allowed to continue playing sound but at a lower volume. We'll treat
// both cases the same way because our app is playing short sound files.
// Pause playback and reset player to the start of the file. That way, we can
// play the word from the beginning when we resume playback.
mediaPlayer.pause();
mediaPlayer.seekTo(0);
Toast.makeText(NumbersActivity.this, "AUDIOFOCUS_LOSS_TRANSIENT", Toast.LENGTH_SHORT).show();
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// The AUDIOFOCUS_GAIN case means we have regained focus and can resume playback.
mediaPlayer.start();
Toast.makeText(NumbersActivity.this, "AUDIOFOCUS_GAIN", Toast.LENGTH_SHORT).show();
}
}
};
在 頁面 創建時首先 實體化 AudioManager 物件, setContentView(R.layout.word_list); 之后添加一行 :
// Create and setup the {@link AudioManager} to request audio focus
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
每當點擊單詞播放音頻時,應該先判斷當前是否具有 Audio Focus 物件,更改 點擊串列項時被回呼的 onItemClick 方法如下:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get the {@link Word} object at the given position the user clicked on
Word clickedWord = adapter.getItem(position);
Toast.makeText(NumbersActivity.this, String.format("item %d clicked.", position), Toast.LENGTH_SHORT).show();
// Release the media player if it currently exists because we are about to
// play a different sound file
releaseMediaPlayer();
// Request audio focus for playback
int result = audioManager.requestAudioFocus(audioFocusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// We have audio focus now.
// Create and setup the {@link MediaPlayer} for the audio resource associated with the current word
mediaPlayer = MediaPlayer.create(NumbersActivity.this, clickedWord.getAudioResourceId());
// Start the audio file
mediaPlayer.start(); // no need to call prepare(); create() does that for you
// Setup a listener on the media player, so that we can stop and release the
// media player once the sound has finished playing.
mediaPlayer.setOnCompletionListener(completionListener);
}
if (result == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {
releaseMediaPlayer();
}
}
同樣,當不再需要播放音頻時,也要將 Audio Focus 釋放掉,更改輔助方法 releaseMediaPlayer 方法如下:
private void releaseMediaPlayer() {
// If the media player is not null, then it may be currently playing a sound.
if (mediaPlayer != null) {
// Regardless of the current state of the media player, release its resources
// because we no longer need it.
mediaPlayer.release();
// Set the media player back to null. For our code, we've decided that
// setting the media player to null is an easy way to tell that the media player
// is not configured to play an audio file at the moment.
mediaPlayer = null;
// Regardless of whether or not we were granted audio focus, abandon it. This also
// unregisters the AudioFocusChangeListener so we don't get anymore callbacks.
audioManager.abandonAudioFocus(audioFocusChangeListener);
}
}
最后 對 另外幾個 頁面 進行同樣的更改即可,
現在 這幾個 型別當中的重復代碼變得越來越多, 因此,也可以考慮再寫一個 Activity 作為 這些 Activity 的父類,將重復的代碼都寫在 父類 的 Activity 當中,如 全域變數,輔助方法這些,
總結
這次 對 Miwok 應用的更改都是針對某一時刻而執行的操作,如 播放音頻時有短信通知等情況,不方便給出具體的實作效果,改天有空再考慮錄個視頻,
了解 安卓應用 中對于 音頻 的管理,不用的音頻型別有有不同的狀態,每一種狀態又會產生不一樣的效果,
參考
android play music on opening app - Stack Overflow
MediaPlayer overview | Android Developers
These pages cover topics relating to recording, storing, and playing back audio and video.
- Supported Media Formats
- MediaRecorder
- Data Storage
MediaPlayer | Android Developers
Developer 開發推廣大使 Ian Lake “正確的 Media Playback” - Big Android BBQ 演講 | Youtube
AdapterView.OnItemClickListener
Asynchronous vs synchronous execution, what does it really mean?
MediaPlayer.OnCompletionListener
How to use setOnCompletionListener method in android.media.MediaPlayer
Managing audio focus | Android Developers
AudioFocusRequest | Android Developers
AudioManager | Android Developers
Managing audio focus | Android Developers
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/249829.html
標籤:其他
上一篇:個性化廣告推薦系統實戰系列(一):任務資料簡介和基本流程梳理
下一篇:智能車硬體入門(寒假第一篇)
