Android通過意圖使用內建的音頻播放器

來源:互聯網
上載者:User

標籤:android   style   blog   http   io   ar   os   使用   java   

假設實現一個音頻檔案的播放,那麼在應用程式中提供播放音頻檔案功能的最簡單的方式是利用內建的“Music(音樂)”應用程式的功能--即使用系統內建的或已安裝好的音樂播放器來播放指定的音頻檔案。


本例比較簡單,以下直接給出源碼:

布局檔案activity_main:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://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;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button = (Button) findViewById(R.id.button);button.setOnClickListener(this);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.button:/** * 將通用android.content.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;}}}

源碼:

點擊下載原始碼


Android通過意圖使用內建的音頻播放器

聯繫我們

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