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

Android 通過 Intent 調用系統內置音頻播放器

編輯:關於 Android 程式設計

如果要在應用中實現音頻文件的播放,最簡單的方式之一就是直接利用系統內置的「音樂」應用程序,也就是調用系統自帶或已安裝的音樂播放器來播放指定的音頻文件。這種方式無需自己實現複雜的播放界面,借助 Intent 即可輕鬆完成。

下面直接給出源代碼。

布局文件 activity_main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="音樂播放器實例" />
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/textView"
        android:text="播放音樂" />
</RelativeLayout>

MainActivity 代碼

package com.mutimediademo3audio;

import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
    private Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                /**
                 * 將通用 Intent.ACTION_VIEW 的數據設置為音頻文件的 URI,
                 * 並指定其 MIME 類型,這樣 Android 就能挑選合適的應用來播放。
                 */
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
                File sdcard = Environment.getExternalStorageDirectory();
                File audioFile = new File(sdcard.getPath() + "/good.mp3");
                // 需在 SD 卡中放置一個名為 good 的 mp3 文件
                intent.setDataAndType(Uri.fromFile(audioFile), "audio/mp3");
                startActivity(intent);
                break;
            default:
                break;
        }
    }
}

核心思路是:構造一個 ACTION_VIEW 的 Intent,把它的數據設置為音頻文件的 URI,並通過 setDataAndType 指定 MIME 類型為 "audio/mp3",系統就會自動調起合適的播放器來播放該音頻。使用前別忘了先在 SD 卡根目錄放一個名為 good.mp3 的測試文件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved