安卓學習日誌 Day07

概述

放寒假了,有點暈車,因此多休息了一天。

今天繼續構建 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.

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章