Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發實例 >> Android MediaPlayer(多媒體播放)

Android MediaPlayer(多媒體播放)

編輯:Android開發實例

Android提供了許多方法來控制播放的音頻/視頻文件和流。其中該方法是通過一類稱為MediaPlayer。

Android是提供MediaPlayer類訪問內置的媒體播放器的服務,如播放音頻,視頻等為了使用MediaPlayer,我們要調用這個類的靜態create() 方法。此方法返回MediaPlayer類的一個實例。它的語法如下:

MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);

第二個參數是要播放的歌曲的名字。必須做出一個新的文件夾下的項目名稱為raw,然後將音樂文件轉換成它。

創建了MediaPlayer對象之後,可以調用一些方法來啟動或停止音樂。這些方法在下面列出。

mediaPlayer.start(); mediaPlayer.pause();

在調用start()方法時,音樂將從頭開始播放。如果此方法是pause() 方法之後再次調用時,音樂將開始從那裡被停住,而不是從頭開始播放。 

要從一開始啟動音樂,必須調用 reset()方法。其語法如下給出:

mediaPlayer.reset();

除了start和pause方法,有用於與音頻/視頻文件更好處理提供的此類其他方法。這些方法如下:

Sr.No 方法及說明 1 isPlaying()
這個方法只是返回真/假,表示是否正在播放歌曲 2 seekTo(positon)
此方法采用的整數和移動的歌曲,以特定的秒 3 getCurrentDuration()
這個方法返回歌曲以毫秒為單位的當前位置 4 getDuration()
這個方法返回歌曲以毫秒為單位的總持續時間 5 reset()
此方法重置媒體播放器 6 release()
此方法釋放附MediaPlayer對象的任何資源 7 setVolume(float leftVolume, float rightVolume)
此方法設置了上下這個播放器音量 8 setDataSource(FileDescriptor fd)
此方法設置音頻/視頻文件的數據源 9 selectTrack(int index)
此方法采用的整數,並選擇該特定索引從列表中的軌道 10 getTrackInfo()
這個方法返回軌道信息的數組

例子

這裡有一個例子演示如何使用的MediaPlayer類。它創建了一個基本的媒體播放器,可以前進,後退,播放和暫停播放歌曲。

為了試驗這個例子,需要一個實際的設備上運行這聽聽聲音。

Steps 描述 1 You will use Eclipse IDE to create an Android application and name it as MediaPlayer under a package com.yiibai.mediaplayer. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs. 2 Modify src/MainActivity.java file to add MediaPlayer code. 3 Modify the res/layout/activity_main to add respective XML components 4 Modify the res/values/string.xml to add necessary string components 5 Create a new folder under MediaPlayer with name as raw and place an mp3 music file in it with name as song.mp3 6 Run the application and choose a running android device and install the application on it and verify the results

Following is the content of the modifed main activity filesrc/com.yiibai.mediaplayer/MainActivity.java.

package com.example.mediaplayer; import java.util.concurrent.TimeUnit; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { public TextView songName,startTimeField,endTimeField; private MediaPlayer mediaPlayer; private double startTime = 0; private double finalTime = 0; private Handler myHandler = new Handler();; private int forwardTime = 5000; private int backwardTime = 5000; private SeekBar seekbar; private ImageButton playButton,pauseButton; public static int oneTimeOnly = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); songName = (TextView)findViewById(R.id.textView4); startTimeField =(TextView)findViewById(R.id.textView1); endTimeField =(TextView)findViewById(R.id.textView2); seekbar = (SeekBar)findViewById(R.id.seekBar1); playButton = (ImageButton)findViewById(R.id.imageButton1); pauseButton = (ImageButton)findViewById(R.id.imageButton2); songName.setText("song.mp3"); mediaPlayer = MediaPlayer.create(this, R.raw.song); seekbar.setClickable(false); pauseButton.setEnabled(false); } public void play(View view){ Toast.makeText(getApplicationContext(), "Playing sound", Toast.LENGTH_SHORT).show(); mediaPlayer.start(); finalTime = mediaPlayer.getDuration(); startTime = mediaPlayer.getCurrentPosition(); if(oneTimeOnly == 0){ seekbar.setMax((int) finalTime); oneTimeOnly = 1; } endTimeField.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) finalTime), TimeUnit.MILLISECONDS.toSeconds((long) finalTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes((long) finalTime))) ); startTimeField.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) startTime), TimeUnit.MILLISECONDS.toSeconds((long) startTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes((long) startTime))) ); seekbar.setProgress((int)startTime); myHandler.postDelayed(UpdateSongTime,100); pauseButton.setEnabled(true); playButton.setEnabled(false); } private Runnable UpdateSongTime = new Runnable() { public void run() { startTime = mediaPlayer.getCurrentPosition(); startTimeField.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) startTime), TimeUnit.MILLISECONDS.toSeconds((long) startTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes((long) startTime))) ); seekbar.setProgress((int)startTime); myHandler.postDelayed(this, 100); } }; public void pause(View view){ Toast.makeText(getApplicationContext(), "Pausing sound", Toast.LENGTH_SHORT).show(); mediaPlayer.pause(); pauseButton.setEnabled(false); playButton.setEnabled(true); } public void forward(View view){ int temp = (int)startTime; if((temp+forwardTime)<=finalTime){ startTime = startTime + forwardTime; mediaPlayer.seekTo((int) startTime); } else{ Toast.makeText(getApplicationContext(), "Cannot jump forward 5 seconds", Toast.LENGTH_SHORT).show(); } } public void rewind(View view){ int temp = (int)startTime; if((temp-backwardTime)>0){ startTime = startTime - backwardTime; mediaPlayer.seekTo((int) startTime); } else{ Toast.makeText(getApplicationContext(), "Cannot jump backward 5 seconds", Toast.LENGTH_SHORT).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }

Following is the modified content of the xml res/layout/activity_main.xml.

<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" > <ImageButton android:id="@+id/imageButton3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_marginBottom="14dp" android:onClick="forward" android:src="@android:drawable/ic_media_ff" /> <ImageButton android:id="@+id/imageButton4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignTop="@+id/imageButton2" android:layout_marginLeft="22dp" android:layout_toRightOf="@+id/imageButton2" android:onClick="rewind" android:src="@android:drawable/ic_media_rew" /> <ImageButton android:id="@+id/imageButton2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/imageButton1" android:layout_marginLeft="14dp" android:layout_toRightOf="@+id/imageButton1" android:onClick="pause" android:src="@android:drawable/ic_media_pause" /> <ImageButton android:id="@+id/imageButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/imageButton3" android:layout_marginLeft="24dp" android:layout_toRightOf="@+id/imageButton3" android:onClick="play" android:src="@android:drawable/ic_media_play" /> <SeekBar android:id="@+id/seekBar1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/imageButton3" android:layout_toLeftOf="@+id/textView2" android:layout_toRightOf="@+id/textView1" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/imageButton3" android:layout_alignTop="@+id/seekBar1" android:text="@string/inital_Time" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/imageButton4" android:layout_alignTop="@+id/seekBar1" android:text="@string/inital_Time" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/imageButton3" android:text="@string/hello_world" android:textAppearance="?android:attr/textAppearanceMedium" /> <ImageView android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_below="@+id/textView3" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView3" android:layout_alignBottom="@+id/textView3" android:layout_toRightOf="@+id/imageButton1" android:text="TextView" /> </RelativeLayout>

Following is the content of the res/values/string.xml.

<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">MediaPlayer</string> <string name="action_settings">Settings</string> <string name="hello_world">Now Playing:</string> <string name="inital_Time">0 min, 0 sec</string> </resources>

Following is the content of AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.yiibai.mediaplayer" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.yiibai.mediaplayer.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

Let's try to run your MediaPlayer application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.

Anroid MediaPlayer Tutorial

Select your mobile device as an option and then check your mobile device which will display your default screen:

Anroid MediaPlayer Tutorial

By default you would see the pause button disabled. Now press play button and it would become disable and pause button become enable. It is shown in the picture below:

Anroid MediaPlayer Tutorial

Uptill now , the music has been playing. Now press the pause button and see the pause notification. This is shown below:

Anroid MediaPlayer Tutorial

Now when you press the play button again, the song will not play from the begining but from where it was paused. Now press the fast forwad or backward button to jump the song forward or backward 5 seconds. A time came when the song cannot be jump forward. At this yiibai , the notification would appear which would be something like this:

Anroid MediaPlayer Tutorial

Your music would remain playing in the background while you are doing other tasks in your mobile. In order to stop it , you have to exit this application from background activities.

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved