編輯:關於Android編程
種方法是調用android自帶的播放器
1 //調用系統自帶播放器
2 Intent intent = new Intent();
3 Uri uri = Uri.parse("http://mul1.tximg.cn/music/group/bbs/mp3/44/100715/1279159638887.mp3?z=909255638");
4 intent.setDataAndType(uri, "audio/*");
5 intent.setAction(Intent.ACTION_VIEW);
6 startActivity(intent);
另一種方法是邊下載邊播放
這只是一種思路,參考別人的代碼,實現分段下載,但是我的代碼還很不完善,這方面不准備繼續下去了。
01 package com.sharpandroid.music.activity;
02
03 import java.io.IOException;
04 import android.app.Activity;
05 import android.content.Intent;
06 import android.net.Uri;
07 import android.os.Bundle;
08 import android.util.Log;
09 import android.view.View;
10 import android.widget.Button;
11 import android.widget.ImageButton;
12 import android.widget.SeekBar;
13 import android.widget.TextView;
14
15 import com.sharpandroid.music.R;
16 import com.sharpandroid.music.StreamingMediaPlay2;
17 import com.sharpandroid.music.StreamingMediaPlayer;
18
19
20 public class MediaPlayer extends Activity {
21
22 private Button streamButton;
23 private ImageButton playButton;
24 private boolean isPlaying;
25 private TextView playTime;
26 private StreamingMediaPlayer audioStreamer;
27 private StreamingMediaPlay2 audioStreamer2;
28
29 @Override
30 public void onCreate(Bundle icicle) {
31
32 super.onCreate(icicle);
33
34 setContentView(R.layout.main);
35 initControls();
36 }
37
38 private void initControls() {
39 playTime=(TextView) findViewById(R.id.playTime);
40 streamButton = (Button) findViewById(R.id.button_stream);
41
42 streamButton.setOnClickListener(new View.OnClickListener() {
43 public void onClick(View view) {
44 startStreamingAudio();
45 }});
46
47 playButton = (ImageButton) findViewById(R.id.button_play);
48 playButton.setEnabled(false);
49 playButton.setOnClickListener(new View.OnClickListener() {
50 public void onClick(View view) {
51 if (audioStreamer2.getMediaPlayer().isPlaying()) {
52 audioStreamer2.getMediaPlayer().pause();
53 playButton.setImageResource(R.drawable.button_play);
54 } else {
55 audioStreamer2.getMediaPlayer().start();
56 //audioStreamer.startPlayProgressUpdater();
57 playButton.setImageResource(R.drawable.button_pause);
58 }
59 isPlaying = !isPlaying;
60 }});
61 }
62
63 private void startStreamingAudio() {
64 final SeekBar progressBar = (SeekBar) findViewById(R.id.progress_bar);
65 if ( audioStreamer != null) {
66 audioStreamer.interrupt();
67 }
68 //調用系統自帶播放器
69 // Intent intent = new Intent();
70 // Uri uri = Uri.parse("http://mul1.tximg.cn/music/group/bbs/mp3/44/100715/1279159638887.mp3?z=909255638");
71 // intent.setDataAndType(uri, "audio/*");
72 // intent.setAction(Intent.ACTION_VIEW);
73 // startActivity(intent);
74 audioStreamer2 = new StreamingMediaPlay2(this, playButton, streamButton, progressBar, playTime);
75 audioStreamer2.startStreaming("http://mul1.tximg.cn/music/group/bbs/mp3/44/100715/1279159638887.mp3?z=909255638",5208, 216);
76 streamButton.setEnabled(false);
77
78 }
79 }
下一個文件
001 package com.sharpandroid.music;
002
003 import java.io.File;
004 import java.io.FileInputStream;
005 import java.io.FileOutputStream;
006 import java.io.IOException;
007 import java.io.InputStream;
008 import java.net.MalformedURLException;
009 import java.net.URL;
010 import java.net.URLConnection;
011
012 import android.content.Context;
013 import android.media.AudioManager;
014 import android.media.MediaPlayer;
015 import android.os.Handler;
016 import android.os.Message;
017 import android.util.Log;
018 import android.widget.Button;
019 import android.widget.ImageButton;
020 import android.widget.SeekBar;
021 import android.widget.TextView;
022
023 public class StreamingMediaPlay2 {
024 private static final int INTIAL_KB_BUFFER = 96*10/8;//assume 96kbps*10secs/8bits per byte
025 private ImageButton playButton;
026 private SeekBar progressBar;
027 private TextView playTime;
028 private long mediaLengthInKb, mediaLengthInSeconds;
029 private int totalKbRead = 0;
030 private File downloadingMediaFile;
031 private Context context;
032 String url ;
033 int progress_leng;
034 private MediaPlayer mediaPlayer;
035 private static final int DOWN_UPDATE = 1;
036 boolean isplay = true;
037 int playe = 0;
038 private static final int DOWN_OVER = 2;
039 private int progress;
040
041 private final Handler handler = new Handler()
042 {
043 @Override
044 public void handleMessage(Message msg) {
045 //super.handleMessage(msg);
046 switch (msg.what) {
047 case DOWN_UPDATE:
048 progressBar.setProgress(progress);
049 break;
050 case DOWN_OVER:
051 System.out.println("下載完成");
052 break;
053 }
054 }
055 };
056 public StreamingMediaPlay2(Context context, ImageButton playButton, Button streamButton, SeekBar progressBar,TextView playTime)
057 {
058 this.context = context;
059 this.playButton = playButton;
060 this.playTime=playTime; //播放的進度時刻
061 this.progressBar = progressBar;
062 }
063
064 public void startStreaming(final String mediaUrl, long mediaLengthInKb, long mediaLengthInSeconds) throws IOException {
065 // this.mediaLengthInKb = mediaLengthInKb;
066 //this.mediaLengthInSeconds = mediaLengthInSeconds;
067 url = mediaUrl;
068 Thread down = new Thread(download);
069 down.start();
070 }
071
072 Runnable download = new Runnable(){
073
074 @Override
075 public void run() {
076 // TODO Auto-generated method stub
077 URLConnection cn;
078 try {
079 cn = new URL(url).openConnection();
080 progress_leng = cn.getContentLength();
081 System.out.println("play-------------------77------長度------"+progress_leng);
082 cn.connect();
083 InputStream stream = cn.getInputStream();
084 if (stream == null) {
085 Log.e(getClass().getName(), "Unable to create InputStream for mediaUrl:" + url);
086 }
087 downloadingMediaFile = new File(context.getCacheDir(),"downloadingMedia.dat");
088 if (downloadingMediaFile.exists()) {
089 downloadingMediaFile.delete(); //如果下載完成則刪除
090 }
091 FileOutputStream out = new FileOutputStream(downloadingMediaFile);
092 byte buf[] = new byte[1024*10];
093 int numread = -1;
094 int s = 0;
095 int count = 0;
096 int a = 0;
097 int sum = 0;
098 FileOutputStream out1 = null;
099 // int totalBytesRead = 0, incrementalBytesRead = 0;
100 while((numread = stream.read(buf))!=-1){
101 byte [] b = new byte[numread];
102 //System.out.println("輸出numread的值-----------"+numread);
103
104 //System.out.println(a+"----輸出numread的值-----------"+sum);
105 if(a==0||a%88==0){
106 File file = new File(context.getCacheDir(),"play"+(++count)+".dat");
107 System.out.println("輸出count的值-----------"+count);
108 out1 = new FileOutputStream(file,true);
109
110 }
111 a++;
112 sum +=numread;
113 if(out1!=null){
114 //b=buf;
115 out1.write(buf,0,numread);
116 }
117 out.write(buf, 0, numread);
118 s+=numread;
119 progress = (int) (((float) s / progress_leng) * 100);
120 handler.sendEmptyMessage(DOWN_UPDATE);
121 if(a==150){
122 System.out.println("下載完成了");
123 //播放音樂
124 Thread thread = new Thread(play);
125 thread.start();
126 handler.sendEmptyMessage(DOWN_OVER);
127 }
128 // totalBytesRead += numread;
129 // incrementalBytesRead += numread;
130 // totalKbRead = totalBytesRead/1000; //totalKbRead表示已經下載的文件大小
131 // testMediaBuffer();
132 // fireDataLoadUpdate();
133 }
134
135 } catch (MalformedURLException e) {
136 // TODO Auto-generated catch block
137 e.printStackTrace();
138 } catch (IOException e) {
139 // TODO Auto-generated catch block
140 e.printStackTrace();
141 }
142 }
143
144
145 };
146 //播放音樂
147 public MediaPlayer getMediaPlayer() {
148 return mediaPlayer;
149 }
150 private MediaPlayer createMediaPlayer(File mediaFile)
151 throws IOException {
152 MediaPlayer mPlayer = new MediaPlayer();
153 mPlayer.setOnErrorListener(
154 new MediaPlayer.OnErrorListener() {
155 public boolean onError(MediaPlayer mp, int what, int extra) {
156 Log.e(getClass().getName(), "Error in MediaPlayer: (" + what +") with extra (" +extra +")" );
157 return false;
158 }
159 });
160 FileInputStream fis = new FileInputStream(mediaFile);
161
162 mPlayer.setDataSource(fis.getFD());//此方法返回與流相關聯的文件說明符。
163 mPlayer.prepare();
164
165 return mPlayer;
166 }
167
168 private void startMediaPlayer() {
169 try {
170 System.out.println("開始播放音樂");
171 File bufferedFile = new File(context.getCacheDir(),"play1" + ".dat");
172 // moveFile(downloadingMediaFile,bufferedFile);
173 Log.e(getClass().getName(),"Buffered File path: " + bufferedFile.getAbsolutePath());
174 Log.e(getClass().getName(),"Buffered File length: " + bufferedFile.length()+"");
175 mediaPlayer = createMediaPlayer(bufferedFile);
176 System.out.println(mediaPlayer.getDuration()+"------開始播放170---------------"+mediaPlayer.getCurrentPosition());
177 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
178 mediaPlayer.start();
179 //startPlayProgressUpdater();
180
181 // playButton.setEnabled(true);
182 } catch (IOException e) {
183 Log.e(getClass().getName(), "Error initializing the MediaPlayer.", e);
184 }
185 }
186 //播放MP3
187 Runnable play = new Runnable() {
188
189 @Override
190 public void run() {
191 // TODO Auto-generated method stub
192 while(isplay){
193 try {
194 System.out.println("開始播放音樂");
195 // File bufferedFile2 = new File(context.getCacheDir(),"play"+ (playe+1)+ ".dat");
196 // if(!bufferedFile2.exists()){
197 // isplay = false;
198 // }
199 File bufferedFile = new File(context.getCacheDir(),"play"+ (++playe)+ ".dat");
200 System.out.println("文件的名字為-------------"+playe);
201 if(bufferedFile.exists()){
202 mediaPlayer = createMediaPlayer(bufferedFile);
203 System.out.println(mediaPlayer.getDuration()+"------開始播放170---------------"+mediaPlayer.getCurrentPosition());
204 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
205 mediaPlayer.start();
206 isplay = false;
207 try {
208 Thread.sleep(120000);
209 isplay = true;
210 } catch (InterruptedException e) {
211 // TODO Auto-generated catch block
212 e.printStackTrace();
213 }
214
215 }
216 else{
217 System.out.println("文件不存在----------------");
218 isplay = false;
219 try {
220 Thread.sleep(10000);
221 isplay = true;
222 } catch (InterruptedException e) {
223 // TODO Auto-generated catch block
224 e.printStackTrace();
225 }
226 }
227
228 //startPlayProgressUpdater();
229
230 // playButton.setEnabled(true);
231 } catch (IOException e) {
232 Log.e(getClass().getName(), "Error initializing the MediaPlayer.", e);
233 }
234 }
235 }
236 };
237
238 }
我這個只是為了驗證是否想法可行,因此第二段音樂是在2分鐘以後才繼續播放的
布局文件
01 <?xml version="1.0" encoding="utf-8"?>
02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03 android:orientation="vertical"
04 android:layout_width="fill_parent"
05 android:layout_height="fill_parent"
06 android:padding="10px"
07 android:background="@drawable/back">
08
09 <TextView android:id="@+id/text_kb_streamed"
10 android:layout_width="fill_parent"
11 android:layout_height="wrap_content"
12 android:textStyle="bold"
13 android:text="流媒體測試"/>
14
15 <Button android:id="@+id/button_stream"
16 android:layout_width="wrap_content"
17 android:layout_height="wrap_content"
18 android:layout_marginTop="10px"
19 style="?android:attr/buttonStyleSmall"
20 android:text="開始緩沖"/>
21
22 <RelativeLayout
23 android:layout_width="wrap_content"
24 android:layout_height="wrap_content"
25 >
26 <SeekBar
27 android:id="@+id/progress_bar"
28 android:layout_height="wrap_content"
29 android:layout_width="200px"
30 style="?android:attr/progressBarStyleHorizontal"
31 />
32 <TextView
33 android:id="@+id/playTime"
34 android:layout_width="wrap_content"
35 android:layout_height="wrap_content"
36 android:layout_toRightOf="@id/progress_bar"
37 android:text="00:00"
38 ></TextView>
39 www.2cto.com
40 </RelativeLayout>
41 <RelativeLayout
42 android:layout_width="wrap_content"
43 android:layout_height="wrap_content"
44 >
45 <ImageButton android:id="@+id/button_play"
46 android:layout_width="wrap_content"
47 android:layout_height="wrap_content"
48 android:layout_marginTop="5px"
49 style="?android:attr/buttonStyleSmall"
50 android:src="@drawable/button_pause"/>
51 </RelativeLayout>
最近很多人在問我,個人App開發者如何去設計UI。 其實這是個人開發者最頭痛的問題,搞技術的人,確實沒法做到面面俱到,不可能花大量的時間去切圖,去做原型設計,去做美工。
Android-webview和js互相調用Android 和 H5 都是移動開發應用的非常廣泛。市面上很多App都是使用Android開發的,但使用Android來開發
android Fragments詳解 Fragment是activity的界面中的一部分或一種行為。你可以把多個Fragment們組合到一個activity中
我們在進行項目開發時,為了提高項目開發效率,方便項目測試中的局部代碼功能測試會用到單元測試。這樣就不用重新運行一遍整個項目。長期以此我們會就節省大量的時間去做其他的事。首