andaroid在线播放Word文档格式.docx
- 文档编号:21363627
- 上传时间:2023-01-30
- 格式:DOCX
- 页数:15
- 大小:117.55KB
andaroid在线播放Word文档格式.docx
《andaroid在线播放Word文档格式.docx》由会员分享,可在线阅读,更多相关《andaroid在线播放Word文档格式.docx(15页珍藏版)》请在冰豆网上搜索。
<
TextViewandroid:
id="
@+id/text_kb_streamed"
android:
wrap_content"
textStyle="
bold"
android:
text="
流媒体测试"
/>
Buttonandroid:
@+id/button_stream"
android:
layout_marginTop="
style="
android:
attr/buttonStyleSmall"
开始缓冲"
RelativeLayout
>
<
SeekBar
@+id/progress_bar"
200px"
attr/progressBarStyleHorizontal"
/>
TextView
@+id/playTime"
layout_toRightOf="
@id/progress_bar"
00:
00"
/TextView>
/RelativeLayout>
ImageButtonandroid:
@+id/button_play"
5px"
style="
src="
@drawable/button_pause"
/LinearLayout>
流媒体类
新建流媒体类StreamingMediaPlayer。
1.构造函数StreamingMediaPlayerStreamingMediaPlayer(Contextcontext,ImageButtonplayButton,ButtonstreamButton,SeekBarprogressBar,TextViewplayTime)传递context(上下文)和主界面UI元素,以便在程序中更新界面。
代码如下;
publicStreamingMediaPlayer(Contextcontext,ImageButtonplayButton,ButtonstreamButton,SeekBarprogressBar,TextViewplayTime)
{
this.context=context;
this.playButton=playButton;
this.playTime=playTime;
//播放的进度时刻
this.progressBar=progressBar;
}
2.startStreaming(finalStringmediaUrl,longmediaLengthInKb,longmediaLengthInSeconds)方法,传递音频的URL以及在更新进度条中使用的两个元素。
在startStreaming()中开启一个线程,然后调用downloadAudioIncrement()方法。
publicvoidstartStreaming(finalStringmediaUrl,longmediaLengthInKb,longmediaLengthInSeconds)throwsIOException{
this.mediaLengthInKb=mediaLengthInKb;
this.mediaLengthInSeconds=mediaLengthInSeconds;
Runnabler=newRunnable(){
publicvoidrun(){
try{
downloadAudioIncrement(mediaUrl);
}catch(IOExceptione){
Log.e(getClass().getName(),"
UnabletoinitializetheMediaPlayerforfileUrl="
+mediaUrl,e);
return;
}
};
newThread(r).start();
3.downloadAudioIncrement(StringmediaUrl)方法通过传递的URL地址下载音频文件,因为多媒体播放器锁定它所播放的文件,所以我们不能简单的追加内容,然后通过testMediaBuffer()方法测试,如果是第一次播放,则判断缓冲的内容是否达到足够的内容,达到的话就调用startMediaPlayer()方法进行播放,如果不是第一次播放的话,并且多媒体已播放的进度和多媒体的总进度的差小于一秒,调用transferBufferToMediaPlayer()方法。
publicvoiddownloadAudioIncrement(StringmediaUrl)throwsIOException{
URLConnectioncn=newURL(mediaUrl).openConnection();
cn.connect();
InputStreamstream=cn.getInputStream();
if(stream==null){
UnabletocreateInputStreamformediaUrl:
"
+mediaUrl);
downloadingMediaFile=newFile(context.getCacheDir(),"
downloadingMedia.dat"
);
if(downloadingMediaFile.exists()){
downloadingMediaFile.delete();
//如果下载完成则删除
}
FileOutputStreamout=newFileOutputStream(downloadingMediaFile);
bytebuf[]=newbyte[16384];
inttotalBytesRead=0,incrementalBytesRead=0;
do{
intnumread=stream.read(buf);
if(numread<
=0)
break;
out.write(buf,0,numread);
totalBytesRead+=numread;
incrementalBytesRead+=numread;
totalKbRead=totalBytesRead/1000;
//totalKbRead表示已经下载的文件大小testMediaBuffer();
fireDataLoadUpdate();
}while(validateNotInterrupted());
stream.close();
if(validateNotInterrupted()){
fireDataFullyLoaded();
}
privatebooleanvalidateNotInterrupted(){
if(isInterrupted){
if(mediaPlayer!
=null){
mediaPlayer.pause();
}
returnfalse;
}else{
returntrue;
privatevoidtestMediaBuffer(){
Runnableupdater=newRunnable(){
publicvoidrun(){
if(mediaPlayer==null){
if(totalKbRead>
=INTIAL_KB_BUFFER){
try{
startMediaPlayer();
}catch(Exceptione){
Log.e(getClass().getName(),"
Errorcopyingbufferedconent."
e);
}elseif(mediaPlayer.getDuration()-mediaPlayer.getCurrentPosition()<
=1000){
transferBufferToMediaPlayer();
handler.post(updater);
4.startMediaPlayer()方法用来播放音频文件,首先调用moveFile()方法将下载的文件复制,用mediaPlayer的API播放文件,startPlayProgressUpdater()方法更新进度条。
privatevoidstartMediaPlayer(){
FilebufferedFile=newFile(context.getCacheDir(),"
playingMedia"
+(counter++)+"
.dat"
moveFile(downloadingMediaFile,bufferedFile);
Log.e(getClass().getName(),"
BufferedFilepath:
"
+bufferedFile.getAbsolutePath());
BufferedFilelength:
+bufferedFile.length()+"
mediaPlayer=createMediaPlayer(bufferedFile);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.start();
startPlayProgressUpdater();
playButton.setEnabled(true);
ErrorinitializingtheMediaPlayer."
5.createMediaPlayer()方法用来得到一个MediaPlayer对象。
privateMediaPlayercreateMediaPlayer(FilemediaFile)
throwsIOException{
MediaPlayermPlayer=newMediaPlayer();
mPlayer.setOnErrorListener(
newMediaPlayer.OnErrorListener(){
publicbooleanonError(MediaPlayermp,intwhat,intextra){
ErrorinMediaPlayer:
("
+what+"
)withextra("
+extra+"
)"
);
returnfalse;
});
FileInputStreamfis=newFileInputStream(mediaFile);
mPlayer.setDataSource(fis.getFD());
//此方法返回与流相关联的文件说明符。
mPlayer.prepare();
returnmPlayer;
6.transferBufferToMediaPlayer()方法将下载的文件复制到一个临时的缓存文件中,暂停音频播放,如果音频正在播放或者多媒体的总长度和多媒体已播放的长度之差小于一秒的时候继续播放。
privatevoidtransferBufferToMediaPlayer(){
try{
booleanwasPlaying=mediaPlayer.isPlaying();
intcurPosition=mediaPlayer.getCurrentPosition();
FileoldBufferedFile=newFile(context.getCacheDir(),"
+counter+"
bufferedFile.deleteOnExit();
mediaPlayer.pause();
mediaPlayer.seekTo(curPosition);
booleanatEndOfFile=mediaPlayer.getDuration()-mediaPlayer.getCurrentPosition()<
=1000;
if(wasPlaying||atEndOfFile){
mediaPlayer.start();
oldBufferedFile.delete();
}catch(Exceptione){
Errorupdatingtonewlyloadedcontent."
7.fireDataLoadUpdate()方法开启一个线程根据已下载的文件大小更新进度条。
privatevoidfireDataLoadUpdate(){
Runnableupdater=newRunnable(){
floatloadProgress=((float)totalKbRead/(float)mediaLengthInKb);
progressBar.setSecondaryProgress((int)(loadProgress*100));
8.fireDataFullyLoaded()方法开启一个线程调用transferBufferToMediaPlayer()方法复制缓存文件,之后播放,然后删除下载的临时文件。
privatevoidfireDataFullyLoaded(){
Runnableupdater=newRunnable(){
publicvoidrun(){
transferBufferToMediaPlayer();
9.startPlayProgressUpdater()方法根据播放的进度更新进度条,并且显示播放的时间进度。
publicvoidstartPlayProgressUpdater(){
floatprogress=(((float)mediaPlayer.getCurrentPosition()/1000)/mediaLengthInSeconds);
progressBar.setProgress((int)(progress*100));
intpos=mediaPlayer.getCurrentPosition();
intmin=(pos/1000)/60;
intsec=(pos/1000)%60;
if(sec<
10)
playTime.setText("
+min+"
:
0"
+sec);
//把音乐播放的进度,转换成时间
else
if(mediaPlayer.isPlaying()){
Runnablenotification=newRunnable(){
publicvoidrun(){
startPlayProgressUpdater();
}
};
handler.postDelayed(notification,1000);
}
10.moveFile(FileoldLocation,FilenewLocation)方法用来实现文件的复制。
publicvoidmoveFile(FileoldLocation,FilenewLocation)
if(oldLocation.exists()){
BufferedInputStreamreader=newBufferedInputStream(newFileInputStream(oldLocation));
BufferedOutputStreamwriter=newBufferedOutputStream(newFileOutputStream(newLocation,false));
byte[]buff=newbyte[8192];
intnumChars;
while((numChars=reader.read(buff,0,buff.length))!
=-1){
writer.write(buff,0,numChars);
}catch(IOExceptionex){
thrownewIOException("
IOExceptionwhentransferring"
+oldLocation.getPath()+"
to"
+newLocation.getPath());
}finally{
if(reader!
=null){
writer.close();
reader.close();
}catch(IOExceptionex){
Log.e(getClass().getName(),"
Errorclosingfileswhentransferring"
+newLocation.getPath());
}else{
thrownewIOException("
Oldlocationdoesnotexistwhentransferring"
业务代码
在MediaPlayer中实现流媒体的测试,通过流媒体的构造函数实例化流媒体类,然后调用流媒体的tartStreaming()方法根据传递的URL地址,实现音乐的在线播放。
packagecom.sharpandroid.music.activity;
importjava.io.IOException;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.util.Log;
importandroid.view.View;
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- andaroid 在线播放