Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 多媒體開發:音頻播放

編輯:關於 Android 程式設計

Android 多媒體開發:音頻播放

如今任何一款名副其實的智能手機都具備音頻播放能力,Android 設備也不例外——你可以在它之上開發音樂播放器、有聲書、播客,或任何圍繞音頻的應用。本文先介紹 Android 支持的格式與編解碼器,再動手寫一個播放示例。

支持的格式

Android 在錄音與播放方面支持多種格式與編解碼器,常見的有 AAC、MP3、AMR、Ogg、PCM 等(具體細節可查閱官方資料)。

借助系統內建播放器

最省事的做法是通過 Intent 讓系統挑選合適的應用來播放。使用 ACTION_VIEW 意圖,把數據設置為音頻文件的 URI,並指定 MIME 類型即可:

Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(audioFileUri, "audio/mp3");
startActivity(intent);

關鍵在於 MIME 類型,形如 audio/mp3,前半是大類,後半是具體格式。與此同時,音頻多媒體在系統中統一存儲於 MediaStore.Audio,裡面包含 Media、Album、Genre 等信息實體。

完整示例

下面的 Activity 監聽一個按鈕的點擊事件,點擊後打開系統自帶的 Music 應用播放指定文件:

public class IntentAudioPlayer extends Activity implements OnClickListener {
    Button playButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        playButton = (Button) this.findViewById(R.id.Button01);
        playButton.setOnClickListener(this);
    }

    public void onClick(View v) {
        Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
        File sdcard = Environment.getExternalStorageDirectory();
        File audioFile = new File(sdcard.getPath() + "/Music/goodmorningandroid.mp3");
        intent.setDataAndType(Uri.fromFile(audioFile), "audio/mp3");
        startActivity(intent);
    }
}

配套的布局文件只需要一個按鈕:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  <Button
    android:text="Play Audio"
    android:id="@+id/Button01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</LinearLayout>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved