本文简介
媒体包提供了可管理各种媒体类型的类。这些类可提供用于执行音频和视频操作。除了基本操作之外,还可提供铃声管理、脸部识别以及音频路由控制。本文说明了音频和视频操作。
范围:
本文旨在针对希望简单了解Android编程的初学者而设计。本文将指导你逐步开发使用媒体(音频和视频)的应用程序。本文假定你已安装了可开发应用程序的Android和必要的工具,同时还假定你已熟悉Java或掌握面向对象的编程概念。如欲查询更多有关Android的详情,请参阅三星移动创新者园地(SMI)知识库网站。http://innovator.samsungmobile.com/cn/platform.main.do?platformId=1
简介
通过“android.media”包支持音频和视频操作。除了基本操作之外,还可以提供用于铃声管理、脸部识别以及音频路由控制的各种类。
Android通过MediaPlayer类支持播放音频和视频。MediaPlayer类处于Android media包的核心位置。除了MediaPlayer类之外,SoundPool和JetPlayer类也可提供用来播放音频文件。
播放音频文件
MediaPlayer
是播放媒体文件最为广泛使用的类。MediaPlayer已设计用来播放大容量的音频文件以及同样可支持播放操作(停止、开始、暂停等)和查找操作的流媒体。其还可支持与媒体操作相关的监听器。通过以下方式可完成播放MediaPlayer中的音频和视频:
· 从源文件播放。
· 从文件系统播放。
· 从流媒体播放。
MediaPlayer监听器
定义了部分监听器,如OnCompletionListener、OnPrepareListener、OnErrorListener、OnBufferingUpdateListener、OnInfoListener,OnVideoSizeChangedListener和OnSeekCompleteListener。当在播放过程中到达媒体源末端时,可调用OnCompletionListener onCompletion(MediaPlayer mp)事件。你也可使用监听器事件来从列表中播放下一首歌曲或释放媒体播放器对象。当准备播放媒体源时,将可调用OnPrepareListener onPrepared(MediaPlayer mp)事件。你可以开始播放onPrepared()方法中的歌曲。当在异步操作过程中出现错误时(其他错误将在调用方法时抛出异常),将可调用OnErrorListener boolean onError(MediaPlayer mp, int what, int extra)事件。参数what指明了已发生错误的类型。这可能为MEDIA_ERROR_UNKNOWN or MEDIA_ERROR_SERVER_DIED。参数extra指明了与错误相关的附加信息。
从res播放音频
这是播放音频文件最普通的方法。在此情况下,音频文件应存在于该项目的raw或assets文件夹中,如图1中所示。
如欲访问一个原资源,仅需使用无扩展名的小写文件名称:
context appContext = getApplicationContext();
MediaPlayer mMediaPlayer = MediaPlayer.create(appContext,R.raw.samplemp3);
mMediaPlayer.start();
或
MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.samplemp3);
mMediaPlayer.start();
如欲停止播放,调用stop()。如果你希望重播该媒体,则须在再次调用start()之前reset()(重置())并prepare()(准备())该MediaPlayer对象。(create()首次调用prepare()。)如欲暂停播放,调用pause()。使用start()可从你已暂停的地方恢复播放。
从文件系统播放音频
访问音频文件的第二种方法是从文件系统,即SD卡。大多数音频资源均存在于SD卡中。在研究如何通过SD卡访问音频文件之前,让我们看一下如何在SD卡中加载文件。通过窗口> 显示视图> 其他,可打开Eclipse IDE中的FileExplorer视图。其将打开显示视图。如图2中所示,选择Android >FileExplorer。
一旦选择File Explorer(文件管理器),即将会打开File Explorer视图,如图3所示。
现在,可将文件推入SD卡中,在File Explorer中选择sdcard文件夹,并使用位于右上角的右箭头来选择按钮。此操作可开启对话框,可使你选择文件。选择你所需上传至SD卡中的文件。将文件推入SD卡中后,如图4中显示了可用的内容。
通过以下方式来从SD卡访问文件
String pathToFile = "/sdcard/samplemp3.mp3";
//create mediaplayer
mediaPlayer = new MediaPlayer();
//set audio file path
try {
mediaPlayer.setDataSource(pathToFile);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Prepare mediaplayer
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//start mediaPlayer
mediaPlayer.start();
首先,创建一个新的MediaPlayer实例。其次,将待播放的音频文件(文件路径)设置为MediaPlayer实例的数据源。在播放器开始播放歌曲之前,必须准备好MediaPlayer对象。prepare()方法为阻塞方法,并可阻塞直至媒体播放器准备播放歌曲。非阻塞方法prepareAsync()也可进行提供。如果媒体播放器用来从流媒体中播放歌曲,并且在播放歌曲之前需要缓冲数据,则应使用非阻塞prepare方法。现在使用以下内容来播放控制方法,如Start()、stop()等。在可设置用于部分其他歌曲文件之前,媒体播放器对象须进行重置。媒体播放器在其使用后须予以释放。此操作使用release()方法来完成。Release()方法可释放与MediaPlayer对象相关联的资源。当你使用MediaPlayer来完成操作时,这被认为是调用此方法的最佳实践。我们也可通过以下方式来创建媒体播放器
String pathToFile = "/sdcard/samplemp3.mp3";
MediaPlayer filePlayer = MediaPlayer.create( appContext, Uri.parse(pathToFile) );
此处可通过解析给定的已编译URI字符串来使用URI类创建Uri。
从网页播放音频
使用与用于访问SD卡中存有的音频文件的相同代码,可完成访问网站中的音频文件。唯一的变化就是文件路径。此处的路径将为网站URL,其指向音频资源文件。此处最重要的部分就是使用互联网提取数据,因此必须获取访问互联网的许可。在AndroidManifest.xml文件中设置互联网许可
<uses-permission android:name="android.permission.INTERNET">
</uses-permission>
除了URL路径外,该代码保持相同
String urlPath = "http:/www.xyz.com/…/samplemp3.mp3";
//create new mediaplayer
mediaPlayer = new MediaPlayer();
//set audio file path
try {
mediaPlayer.setDataSource(urlPath);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Prepare mediaplayer
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Start mediaplayer
mediaPlayer.start();
或者,我们也可通过以下方式创建媒体播放器
String urlPath = "http:/www.xyz.com/…/samplemp3.mp3";
MediaPlayer filePlayer = MediaPlayer.create( appContext, Uri.parse(urlPath) );
此处可通过解析给定的已编译URI字符串来使用URI类创建Uri。类与MediaPlayer类相对。该类设计用于快速播放一套预先定义的相对较短的声音示例。它是示例的集合,这些示例可从APK内部的资源或从文件系统的文件载入内存中。最典型的用例是在要求低延时的游戏中的音效池。除了预先加载和播放声音等基本操作外,SoundPool类还支持以下功能:
SoundPool
SoundPool
· 设置可同时播放的最高的声音数
· 优先处理声音,以便达到最大极限时将会减弱优先级别低的声音
· 在完成播放之前暂停和停止声音
· 循环声音
· 更改播放速率(实际上是指每个声音音调)
· 设置立体声音量(左声道和右声道不同)
如图1所示,通过SoundPool类使用.ogg文件来播放音频文件。以下代码片段说明了SoundPool类的用法。
private int BIG_WAVE = 1;
/*
Initialize SoundPool
1 – number of sounds that will be loaded.
AudioManager.STREAM_MUSIC- Stream type
0 – Quality of the sound. Currently no effect
*/
SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
//Create HashMap
HashMap soundPoolMap = new HashMap();
//Create AudioManager
AudioManager mAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
OR
AudioManager mAudioManager =
(AudioManager)getContext().getSystemService(AUDIO_SERVICE);
//Load audio file
int soundID = mSoundPool.load(this, R.raw.bigwave, 1);
//Put key value pair in HashMap
soundPoolMap.put(BIG_WAVE, soundID);
//Play sound
int streamVolume =
mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int actualVolume =
mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVolume =
mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
soundPool.play(
mSoundPoolMap.get(BIG_WAVE), streamVolume, streamVolume, 1, 0, 1f);
从res播放音频
使用SoundPool类load (Context context, int resId, int priority)方法可从原文件夹加载音频文件。如果你希望从原资源文件“bigwave.mp3”加载声音,则应将“R.raw.bigwave”指定为资源ID。返回可被使用的整数值SoundID来播放声音。
从文件系统播放音频
使用SoundPool类load (String path, int priority)方法可从原文件夹加载音频文件。如果你希望从原资源文件“bigwave.mp3”加载声音,则应将“R.raw.bigwave”指定为资源ID。此操作能返回可被使用的整数值SoundID来播放声音。
ToneGenerator
该类提供了可播放双音多频(DTMF)音、呼叫监控音和专有音的各种方法。对象要求一个输出流类型和音量。startTone()可用来播放声音。startTone()方法可在指定的时间段开始播放指定类型的声音。
ToneGenerator
//Output Stream Type and Volume
ToneGenerator tg=new ToneGenerator(AudioManager.STREAM_RING, 100);
//Play Tone
tg.startTone(ToneGenerator.TONE_CDMA_ABBR_ALERT);
播放视频文件
VideoView
Android提供了专业化的视图控制android.widget.VideoView,其可压缩创建并初始化MediaPlayer。VideoView类可从各种源(如资源或内容提供商)加载图片,并且可负责从该视频计算其尺寸,以便其可在任何布局管理器中使用。同样,该类还可提供各种显示选项,如缩放比例和着色。可用来显示SDCard FileSystem中存在的视频文件或联机存在的文件。如欲添加VideoView控件,res文件夹中存在的布局文件将可能出现如下情况
VideoView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
<VideoView
android:id="@+id/videoView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
并且显示如下代码片段
//Create VideoView
VideoView videoView = (VideoView)this.findViewById(R.id.videoView);
//Create MediaController
MediaController mc = new MediaController(this);
//Set MediaController to VideoView
videoView.setMediaController(mc);
//Set video path of SD Card
videoView.setVideoURI(Uri.parse("file:///sdcard/samplemp4.mp4"));
OR
//Set video web path
videoView.setVideoURI(Uri.parse("http://www.xyz.com/../sample3gp.3gp"));
//Set requestFocus
videoView.requestFocus();
//Play Video
videoView.start();
从文件系统播放视频从将访问视频文件的地方设置视频路径。此处指定了文件系统的路径。使用Uri.parse(String path)静态方法,其可将该字符串转换为Uri。从网页播放视频此操作与从文件系统播放视频的方法相同,唯一的区别就是路径。此处的路径指向网站。
VideoView setVideoURI(Uri uri)
SurfaceView
可允许我们指定我们自己的显示面,并可允许直接操控媒体播放器基础实例。如欲使用媒体播放器来查看视频内容,首先要准备一个将可显示该视频的显示面。媒体播放器要求一个SurfaceHolder对象来显示视频内容,该对象可使用setDisplay()方法来予以分配。如欲在UI布局中包括Surface Holder,使用存在于res文件夹中的布局文件中的SurfaceView控件。
SurfaceView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<SurfaceView android:id="@+id/surface"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
</SurfaceView>
</LinearLayout>
以下代码片段说明了如何创建SurfaceView和SurfaceHolder。
//create SurfaceView
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surface);
//get SurfaceHolder
SurfaceHolder holder = mPreview.getHolder();
//add callback
holder.addCallback(this);
//set Surface Type
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
//set Surface size
Holder.setFixedSize(width, height); //specify the width and height here
如欲显示视频,需要执行SurfaceHolder.Callback接口。SurfaceHolder.Callback接口有三种方法
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}
类有助于我们控制表面(如果表面发生变化,包括大小或表面的格式…)。一旦已创建表面,即可调用surfaceCreated(SurfaceHolder holder)。然后,创建一个MediaPlayer对象并设定其他参数。
SurfaceHolder
从res播放视频
此处需要使用MediaPlayer 静态方法MediaPlayer create (Context context, int resid)来创建MediaPlayer对象。该媒体播放器要求一个SurfaceHolder对象来显示视频内容,该对象可使用setDisplay()方法来予以分配。
//Create MediaPlayer from res
MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.samplemp4);
//Set the display
mMediaPlayer.setDisplay(holder);
//Set other parameters
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//start the player
mMediaPlayer.start();
从文件系统播放视频
在此情况下,需要使用setDataSource (String path)方法来将文件路径设置为MediaPlayer。然后,需要使用prepare()方法来准备mediaplayer。prepare()方法可同步准备播放器进行播放。设置datasource和显示面后,你需要调用prepare()或prepareAsync()。使用try–catch Exception语句,因为特定的方法(如setDataSource()、prepare())可能会抛出异常。
String pathToFile = "/sdcard/samplemp4.mp4";
// Create a new media player and set the listeners
MediaPlayer mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(pathToFile);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
// set listeners, if required by application
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.start();
从网页播放视频
在此情况下,文件路径需要予以变更,并设置至可访问视频的网站。其他的仍保持相同。
String pathToFile = "http://www.xyz.com/.../samplemp4.mp4";
// Create a new media player and set the listeners
MediaPlayer mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(pathToFile);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
// set listeners, if required by application
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.start();
示例
以下示例说明了可播放res文件夹、系统文件和互联网中存在的音频和视频文件的ediaPlayer、SoundPool、 ToneGenerator、VideoView、SurfaceView类和MediaPlayer监听器的用法。一旦开启,该应用程序即可显示两个选项,即音频或视频。Xml和代码如下所列出
main.xml
<<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<<Button android:text="Audio"
android:id="@+id/button1"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<</Button>
<<Button android:text="Video"
android:id="@+id/button2"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<</Button>
</LinearLayout>
AudioVideoPlayer
package com.samsung.player;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AudioVideoPlayer extends Activity implements OnClickListener{
private Button btnAudio;
private Button btnVideo;
public static final int AUDIO = 1;
public static final int VIDEO = 2;
public static final String PLAY_WHAT = "AUDIO_VIDEO";
public static final String PLAY_AUDIO = "AUDIO";
public static final String PLAY_VIDEO = "VIDEO";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnAudio = (Button)findViewById(R.id.button1);
btnAudio.setOnClickListener(this);
btnVideo = (Button)findViewById(R.id.button2);
btnVideo.setOnClickListener(this);
}
public void onClick(View v) {}
if(v == btnAudio) {
Intent intent = new Intent(this.getApplication(),MyPlayerMenu.class);
intent.putExtra(PLAY_WHAT, AUDIO);
startActivity(intent);
} else
if(v == btnVideo) {
Intent intent = new Intent(this.getApplication(),MyPlayerMenu.class);
intent.putExtra(PLAY_WHAT, VIDEO);
startActivity(intent);
}
}
一旦选择音频,该应用程序即可显示以下所列出的音频菜单
myplayermenu.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:text="Play Audio from res"
android:id="@+id/menubutton1"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</Button>
<Button android:text="Play Audio from filesystem"
android:id="@+id/menubutton2"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</Button>
<Button android:text="Play Audio from web stream"
android:id="@+id/menubutton3"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</Button>
<Button android:text="Play Audio Tone (ToneGenerator)"
android:id="@+id/menubutton4"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</Button>
<Button android:text="SoundPool"
android:id="@+id/menubutton5"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</Button>
</LinearLayout>
MyPlayerMenu
package com.samsung.player;
import android.app.Activity;
import android.content.Intent;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MyPlayerMenu extends Activity implements OnClickListener {
private Button btnRes;
private Button btnFile;
private Button btnWeb;
private Button btnTone;
private Button btnSoundPool;
private int value;
public static final int PLAY_AUDIO_FROM_RES = 3;
public static final int PLAY_AUDIO_FROM_FILESYSTEM = 4;
public static final int PLAY_AUDIO_FROM_WEB = 5;
public static final int PLAY_AUDIO_FROM_TONE = 6;
public static final int PLAY_AUDIO_FROM_SOUNDPOOL = 7;
public static final int PLAY_VIDEO_FROM_RES = 8;
public static final int PLAY_VIDEO_FROM_FILESYSTEM = 9;
public static final int PLAY_VIDEO_FROM_WEB = 10;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myplayermenu);
btnRes = (Button)findViewById(R.id.menubutton1);
btnRes.setOnClickListener(this);
btnFile = (Button)findViewById(R.id.menubutton2);
btnFile.setOnClickListener(this);
btnWeb = (Button)findViewById(R.id.menubutton3);
btnWeb.setOnClickListener(this);
btnTone = (Button)findViewById(R.id.menubutton4);
btnTone.setOnClickListener(this);
btnSoundPool = (Button)findViewById(R.id.menubutton5);
btnSoundPool.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
value = extras.getInt(AudioVideoPlayer.PLAY_WHAT);
if(value == AudioVideoPlayer.VIDEO) {
btnRes.setText("Play Video from res");
btnFile.setText("Play Video from file");
btnWeb.setText("Play Video from web");
btnTone.setEnabled(false);
btnSoundPool.setEnabled(false);
}else
if(value == AudioVideoPlayer.AUDIO) {
btnRes.setText("Play Audio from res");
btnFile.setText("Play Audio from file");
btnWeb.setText("Play Audio from web");
btnTone.setEnabled(true);
btnSoundPool.setEnabled(true);
}
}
public void onClick(View v) {
if(v == btnRes) {
Intent intent = null;
if(value == AudioVideoPlayer.AUDIO) {
intent = new Intent(this.getApplication(),MyAudioPlayer.class);
intent.putExtra(AudioVideoPlayer.PLAY_AUDIO, PLAY_AUDIO_FROM_RES);
}else
{
intent = new Intent(this.getApplication(),MySurfaceViewVideoPlayer.class);
intent.putExtra(AudioVideoPlayer.PLAY_VIDEO, PLAY_VIDEO_FROM_RES);
}
startActivity(intent);
}else
if(v == btnFile) {
Intent intent = null;
if(value == AudioVideoPlayer.AUDIO) {
intent = new Intent(this.getApplication(),MyAudioPlayer.class);
intent.putExtra(AudioVideoPlayer.PLAY_AUDIO, PLAY_AUDIO_FROM_FILESYSTEM);
} else
{
intent = new Intent(this.getApplication(),MyVideoPlayerMenu.class);
intent.putExtra(AudioVideoPlayer.PLAY_VIDEO, PLAY_VIDEO_FROM_FILESYSTEM);
}
startActivity(intent);
}else
if(v == btnWeb) {
Intent intent = new Intent(this.getApplication(),MyAudioPlayer.class);
if(value == AudioVideoPlayer.AUDIO) {
intent.putExtra(AudioVideoPlayer.PLAY_AUDIO, PLAY_AUDIO_FROM_WEB);
}else
{
intent = new Intent(this.getApplication(),MyVideoPlayerMenu.class);
intent.putExtra(AudioVideoPlayer.PLAY_VIDEO, PLAY_VIDEO_FROM_WEB);
}
startActivity(intent);
}else
if(v == btnTone) {
ToneGenerator tg=new ToneGenerator(AudioManager.STREAM_RING, 100);
tg.startTone(ToneGenerator.TONE_CDMA_ABBR_ALERT);
}else
if(v == btnSoundPool) {
Intent intent = new Intent(this.getApplication(),MySoundPoolAudioPlayer.class);
intent.putExtra(AudioVideoPlayer.PLAY_AUDIO, PLAY_AUDIO_FROM_SOUNDPOOL);
startActivity(intent);
}
}
}
一旦从res、文件系统和网页选择音频,则MyAudioPlayer可获调用。
myaudioplayer.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/myaudioplayer"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:text="Text"
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button android:text="Play"
android:id="@+id/playButton"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</Button>
</LinearLayout>
MyAudioPlayer
package com.samsung.player;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MyAudioPlayer extends Activity implements OnClickListener{
private Button btnPausePlay;
private MediaPlayer mediaPlayer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myaudioplayer);
btnPausePlay = (Button)findViewById(R.id.playButton);
btnPausePlay.setOnClickListener(this);
btnPausePlay.setText("Pause");
Bundle extras = getIntent().getExtras();
int value = extras.getInt(AudioVideoPlayer.PLAY_AUDIO);
playAudio(value);
}
private void playAudio(int value) {
if(value == MyPlayerMenu.PLAY_AUDIO_FROM_RES) {
mediaPlayer = MediaPlayer.create(this, R.raw.samplemp3);
mediaPlayer.start();
} else
if(value == MyPlayerMenu.PLAY_AUDIO_FROM_FILESYSTEM) {
String pathToFile = "/sdcard/samplemp3.mp3";
//Uri uri = Uri.parse(pathToFile);
//mediaPlayer = MediaPlayer.create(this, uri);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(pathToFile);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
} else
if(value == MyPlayerMenu.PLAY_AUDIO_FROM_WEB) {
String pathToFile = "http://www.xyz.com/Audio/sample.mp3";
//Uri uri = Uri.parse(pathToFile);
//mediaPlayer = MediaPlayer.create(this, uri);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(pathToFile);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
}
// Initiate media player pause
private void demoPause(){
mediaPlayer.pause();
btnPausePlay.setText("Play");
}
// Initiate playing the media player
private void demoPlay(){
mediaPlayer.start();
btnPausePlay.setText("Pause");
}
public void onClick(View v) {
if(v == btnPausePlay) {
if(mediaPlayer.isPlaying()) {
demoPause();
} else {
demoPlay();
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
}
private void releaseMediaPlayer() {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
}
一旦选择SoundPool,该应用程序即可显示如下显示的SoundPool菜单
mysoundpoolplayermenu.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:text="BigWave"
android:id="@+id/soundbutton1"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</Button>
<Button android:text="FlameMagic"
android:id="@+id/soundbutton2"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</Button>
<Button android:text="MetalHit"
android:id="@+id/soundbutton3"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</Button>
<Button android:text="TornadoMagic"
android:id="@+id/soundbutton4"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</Button>
</LinearLayout>
MySoundPoolAudioPlayer
package com.samsung.player;
import java.util.HashMap;
import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MySoundPoolAudioPlayer extends Activity implements OnClickListener{
private Button btnBigWave;
private Button btnFlameMagic;
private Button btnMetalHit;
private Button btnTornadoMagic;
private SoundPool mSoundPool;
private HashMap mSoundPoolMap;
private AudioManager mAudioManager;
public static final int BIG_WAVE = 11;
public static final int FLAME_MAGIC = 12;
public static final int METAL_HIT = 13;
public static final int TORNADO = 14;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mysoundpoolplayermenu);
btnBigWave = (Button)findViewById(R.id.soundbutton1);
btnBigWave.setOnClickListener(this);
btnFlameMagic = (Button)findViewById(R.id.soundbutton2);
btnFlameMagic.setOnClickListener(this);
btnMetalHit = (Button)findViewById(R.id.soundbutton3);
btnMetalHit.setOnClickListener(this);
btnTornadoMagic = (Button)findViewById(R.id.soundbutton4);
btnTornadoMagic.setOnClickListener(this);
loadSoundPool();
}
private void loadSoundPool() {
mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
mSoundPoolMap = new HashMap();
mAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
int soundID = mSoundPool.load(this, R.raw.bigwave, 1);
//OR
//String pathToFile = "/sdcard/bigwave.ogg";
//int soundID = mSoundPool.load(pathToFile, 1);
addSound(BIG_WAVE, soundID);
soundID = mSoundPool.load(this, R.raw.flamemagic, 1);
addSound(FLAME_MAGIC, soundID);
soundID = mSoundPool.load(this, R.raw.metalhit, 1);
addSound(METAL_HIT, soundID);
soundID = mSoundPool.load(this, R.raw.tornadomagic, 1);
addSound(TORNADO, soundID);
}
private void addSound(int index, int SoundID) {
mSoundPoolMap.put(index, SoundID);
}
public void playAudio(int index) {
int streamVolume =
mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
/*float actualVolume =
(float) mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume =
(float) mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float streamVolume = actualVolume / maxVolume;
*/
mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);
}
public void playLoopAudio(int index) {
int streamVolume =
mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, -1, 1f);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public void onClick(View v) {
if(v == btnBigWave) {
playAudio(BIG_WAVE);
}else
if(v == btnFlameMagic) {
playAudio(FLAME_MAGIC);
}else
if(v == btnMetalHit) {
playAudio(METAL_HIT);
}else
if(v == btnTornadoMagic) {
playAudio(TORNADO);
}
}
}
同样,一旦从AudioVideoPlayer类中显示的主菜单选择视频选项,则其可显示子菜单为该xml和类中所显示的VideoView和SurfaceView。
myvideoplayermenu.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:text="Play using VideoView"
android:id="@+id/menubutton1"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</Button>
<Button android:text="Play using SurfaceView"
android:id="@+id/menubutton2"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</Button>
</LinearLayout>
MyVideoPlayerMenu
package com.samsung.player;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MyVideoPlayerMenu extends Activity implements OnClickListener{
private Button btnVideoView;
private Button btnSurfaceView;
private int value;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myvideoplayermenu);
btnVideoView = (Button)findViewById(R.id.menubutton1);
btnVideoView.setOnClickListener(this);
btnSurfaceView = (Button)findViewById(R.id.menubutton2);
btnSurfaceView.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
value = extras.getInt(AudioVideoPlayer.PLAY_VIDEO);
}
public void onClick(View v) {
if(v == btnVideoView) {
Intent intent = new Intent(this.getApplication(),MyVideoViewVideoPlayer.class);
intent.putExtra(AudioVideoPlayer.PLAY_VIDEO, value);
startActivity(intent);
}else
if(v == btnSurfaceView) {
Intent intent = new Intent(this.getApplication(),MySurfaceViewVideoPlayer.class);
intent.putExtra(AudioVideoPlayer.PLAY_VIDEO, value);
startActivity(intent);
}
}
}
如选择了VideoView则VideoView将显示在xml以及类文件的列表中
myvideoviewvideoplayer
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<VideoView
android:id="@+id/videoView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
MyVideoViewVideoPlayer
package com.samsung.player;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
public class MyVideoViewVideoPlayer extends Activity {
private VideoView videoView;
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.myvideoviewvideoplayer);
videoView = (VideoView)this.findViewById(R.id.videoView);
MediaController mc = new MediaController(this);
videoView.setMediaController(mc);
Bundle extras = getIntent().getExtras();
int value = extras.getInt("VIDEO");
playVideo(value);
}
private void playVideo(int value) {
if(value == MyPlayerMenu.PLAY_VIDEO_FROM_FILESYSTEM) {file:///sdcard/samplemp4.mp4"));
videoView.setVideoURI(Uri.parse("
videoView.requestFocus();
videoView.start();
} else
if(value == MyPlayerMenu.PLAY_VIDEO_FROM_WEB) { http://www.xyzo.com/.../sample3gp.3gp"));
videoView.setVideoURI(Uri.parse("
videoView.requestFocus();
videoView.start();
}
}
}
mysurfaceviewvideoplayer.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SurfaceView android:id="@+id/surface"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
</SurfaceView>
</LinearLayout>
MySurfaceViewVideoPlayer
package com.samsung.player;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MySurfaceViewVideoPlayer extends Activity implements
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback {
private int mVideoWidth;
private int mVideoHeight;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
private MediaPlayer mMediaPlayer;
private SurfaceView mPreview;
private SurfaceHolder holder;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.mysurfaceviewvideoplayer);
mPreview = (SurfaceView) findViewById(R.id.surface);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
if (width == 0 || height == 0) { return; }
mIsVideoSizeKnown = true;
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void onPrepared(MediaPlayer mediaplayer) {
mIsVideoReadyToBePlayed = true;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
}
public void surfaceDestroyed(SurfaceHolder surfaceholder) {
}
public void surfaceCreated(SurfaceHolder holder) {
Bundle extras = getIntent().getExtras();
int value = extras.getInt(AudioVideoPlayer.PLAY_VIDEO);
playVideo(value);
}
private void playVideo(Integer value) {
doCleanUp();
try {
switch (value) {
case MyPlayerMenu.PLAY_VIDEO_FROM_RES:
mMediaPlayer = MediaPlayer.create(this, R.raw.samplemp4);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.start();
break;
case MyPlayerMenu.PLAY_VIDEO_FROM_FILESYSTEM:
String pathToFile = "/sdcard/samplemp4.mp4";
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(pathToFile);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
break;
case MyPlayerMenu.PLAY_VIDEO_FROM_WEB: http://www.xyz.com/.../sample3gp.3gp";
String pathToWeb= "
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(pathToWeb);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
break;
}
} catch (Exception e) {
}
}
@Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
doCleanUp();
}
@Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
doCleanUp();
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
private void doCleanUp() {
mVideoWidth = 0;
mVideoHeight = 0;
mIsVideoReadyToBePlayed = false;
mIsVideoSizeKnown = false;
}
private void startVideoPlayback() {
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
}
}
以下是AndroidManifest.xml文件
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samsung.player"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AudioVideoPlayer"
android:label="@string/app_name">
<intent-filter>
</intent-filter>
</activity>
<activity android:name=".MyPlayerMenu" android:label="PlayerMenu">
<intent-filter>
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name=".MyAudioPlayer" android:label="AudioPlayer">
<intent-filter>
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name=".MySoundPoolAudioPlayer" android:label="SoundPool AudioPlayer">
<intent-filter>
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name=".MyVideoPlayerMenu" android:label="VideoPlayerMenu">
<intent-filter>
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name=".MySurfaceViewVideoPlayer" android:label="SurfaceView VideoPlayer">
<intent-filter>
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name=".MyVideoViewVideoPlayer" android:label="VideoView VideoPlayer">
<intent-filter>
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET">
</uses-permission>
</manifest>