android在线播放音乐

android在线音乐

一种方法是调用android自带的播放器

//调用系统自带播放器
		Intent intent = new Intent();
		Uri uri = Uri.parse("http://mul1.tximg.cn/music/group/bbs/mp3/44/100715/1279159638887.mp3?z=909255638");
		intent.setDataAndType(uri, "audio/*");
		intent.setAction(Intent.ACTION_VIEW);
		startActivity(intent);

另一种方法是边下载边播放

这只是一种思路,参考别人的代码,实现分段下载,但是我的代码还很不完善,这方面不准备继续下去了。

 

package com.sharpandroid.music.activity;

import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

import com.sharpandroid.music.R;
import com.sharpandroid.music.StreamingMediaPlay2;
import com.sharpandroid.music.StreamingMediaPlayer;


public class MediaPlayer extends Activity {

	private Button streamButton;
	private ImageButton playButton;
	private boolean isPlaying;
	private TextView playTime;
	private StreamingMediaPlayer audioStreamer;
	private StreamingMediaPlay2 audioStreamer2;
	
    @Override
	public void onCreate(Bundle icicle) {
    	
        super.onCreate(icicle);

        setContentView(R.layout.main);
        initControls();
    } 
    
    private void initControls() {
    	playTime=(TextView) findViewById(R.id.playTime);
		streamButton = (Button) findViewById(R.id.button_stream);
		
		streamButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				startStreamingAudio();
        }});

		playButton = (ImageButton) findViewById(R.id.button_play);
		playButton.setEnabled(false);
		playButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (audioStreamer2.getMediaPlayer().isPlaying()) {
					audioStreamer2.getMediaPlayer().pause();
					playButton.setImageResource(R.drawable.button_play);
				} else {
					audioStreamer2.getMediaPlayer().start();
					//audioStreamer.startPlayProgressUpdater();
					playButton.setImageResource(R.drawable.button_pause);
				}
				isPlaying = !isPlaying;
        }});
    }
    
    private void startStreamingAudio() {
    	final SeekBar progressBar = (SeekBar) findViewById(R.id.progress_bar);
		if ( audioStreamer != null) {
			audioStreamer.interrupt();
		}
		//调用系统自带播放器
//		Intent intent = new Intent();
//		Uri uri = Uri.parse("http://mul1.tximg.cn/music/group/bbs/mp3/44/100715/1279159638887.mp3?z=909255638");
//		intent.setDataAndType(uri, "audio/*");
//		intent.setAction(Intent.ACTION_VIEW);
//		startActivity(intent);
    		audioStreamer2 = new StreamingMediaPlay2(this, playButton, streamButton,  progressBar, playTime);
      		audioStreamer2.startStreaming("http://mul1.tximg.cn/music/group/bbs/mp3/44/100715/1279159638887.mp3?z=909255638",5208, 216);
    		streamButton.setEnabled(false);
    	    	
    }
}

 下一个文件

package com.sharpandroid.music;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

public class StreamingMediaPlay2 {
	private static final int INTIAL_KB_BUFFER =  96*10/8;//assume 96kbps*10secs/8bits per byte
	private ImageButton playButton;
	private SeekBar 	progressBar;
	private TextView playTime;
	private long mediaLengthInKb, mediaLengthInSeconds;
	private int totalKbRead = 0;
	private File downloadingMediaFile;
	private Context context;
	String url ;
	int progress_leng;
	private MediaPlayer 	mediaPlayer;
	private static final int DOWN_UPDATE = 1;
	boolean isplay = true;
	int playe = 0;
	private static final int DOWN_OVER = 2;
	private int progress;
	
	private final Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg) {
			//super.handleMessage(msg);
			switch (msg.what) {
			case DOWN_UPDATE:
				progressBar.setProgress(progress);
				break;
			case DOWN_OVER:
				System.out.println("下载完成");
				break;
			}
		}
	};
	public StreamingMediaPlay2(Context  context, ImageButton	playButton, Button	streamButton, SeekBar	progressBar,TextView playTime) 
 	{
 		this.context = context;
		this.playButton = playButton;
		this.playTime=playTime; //播放的进度时刻
		this.progressBar = progressBar;
	}
	
	public void startStreaming(final String mediaUrl, long	mediaLengthInKb, long	mediaLengthInSeconds) throws IOException {
    //	this.mediaLengthInKb = mediaLengthInKb;
    	//this.mediaLengthInSeconds = mediaLengthInSeconds;
		url = mediaUrl;
		Thread down = new Thread(download);
		down.start();
    }
	
	Runnable download = new Runnable(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
			URLConnection cn;
			try {
				cn = new URL(url).openConnection();
				progress_leng = cn.getContentLength();
				System.out.println("play-------------------77------长度------"+progress_leng);
				cn.connect();        
	        InputStream stream = cn.getInputStream();
	        if (stream == null) {
	        	Log.e(getClass().getName(), "Unable to create InputStream for mediaUrl:" + url);
	        }
			downloadingMediaFile = new File(context.getCacheDir(),"downloadingMedia.dat");			
			if (downloadingMediaFile.exists()) {
				downloadingMediaFile.delete();          //如果下载完成则删除
			}
	        FileOutputStream out = new FileOutputStream(downloadingMediaFile);   
	        byte buf[] = new byte[1024*10];
	        int numread = -1;
	        int s = 0;
	        int count = 0;
	        int a = 0;
	        int sum = 0;
	        FileOutputStream out1 = null;
	      //  int totalBytesRead = 0, incrementalBytesRead = 0;
	        while((numread = stream.read(buf))!=-1){	        	
	        	byte [] b = new byte[numread];
	        	//System.out.println("输出numread的值-----------"+numread);
	        	
	        	//System.out.println(a+"----输出numread的值-----------"+sum);
	        	if(a==0||a%88==0){	        		
	        		File file = new File(context.getCacheDir(),"play"+(++count)+".dat");
	        		System.out.println("输出count的值-----------"+count);
		        	 out1 = new FileOutputStream(file,true);
		        	
	        	} 
	        	 a++;
	        	sum +=numread;
	        	if(out1!=null){
	        	//b=buf;
        		out1.write(buf,0,numread);
	        	}
	            out.write(buf, 0, numread);
	            s+=numread;
	            progress = (int) (((float) s / progress_leng) * 100);
	            handler.sendEmptyMessage(DOWN_UPDATE);
	            if(a==150){
	            	System.out.println("下载完成了");
	            	//播放音乐
	            	Thread thread = new Thread(play);
	            	thread.start();
	            	 handler.sendEmptyMessage(DOWN_OVER);
	            }
	         //   totalBytesRead += numread;
	       //     incrementalBytesRead += numread;
	        //    totalKbRead = totalBytesRead/1000;  //totalKbRead表示已经下载的文件大小
	           // testMediaBuffer();
	        //   	fireDataLoadUpdate();
	        }   
	       		
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}   
		}
		
		
	};
	//播放音乐
	 public MediaPlayer getMediaPlayer() {
	    	return mediaPlayer;
		}
	    private MediaPlayer createMediaPlayer(File mediaFile)
	    throws IOException {
	    	MediaPlayer mPlayer = new MediaPlayer();
	    	mPlayer.setOnErrorListener(
					new MediaPlayer.OnErrorListener() {
				        public boolean onError(MediaPlayer mp, int what, int extra) {
				        	Log.e(getClass().getName(), "Error in MediaPlayer: (" + what +") with extra (" +extra +")" );
				    		return false;
				        }
				    });
			FileInputStream fis = new FileInputStream(mediaFile);
			
			mPlayer.setDataSource(fis.getFD());//此方法返回与流相关联的文件说明符。
			mPlayer.prepare();
			
			return mPlayer;
	    }
	    
	    private void startMediaPlayer() {
	        try {   
	        	System.out.println("开始播放音乐");
	        	File bufferedFile = new File(context.getCacheDir(),"play1" + ".dat");
	        //	moveFile(downloadingMediaFile,bufferedFile);
	        	Log.e(getClass().getName(),"Buffered File path: " + bufferedFile.getAbsolutePath());
	        	Log.e(getClass().getName(),"Buffered File length: " + bufferedFile.length()+"");
	        	mediaPlayer = createMediaPlayer(bufferedFile);
	        	System.out.println(mediaPlayer.getDuration()+"------开始播放170---------------"+mediaPlayer.getCurrentPosition());	        	
	        	mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		    	mediaPlayer.start();
		    	//startPlayProgressUpdater();    
		    
			//	playButton.setEnabled(true);
	        } catch (IOException e) {
	        	Log.e(getClass().getName(), "Error initializing the MediaPlayer.", e);
	        }   
	    }
	    //播放MP3
	Runnable play = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while(isplay){
				  try {   
			        	System.out.println("开始播放音乐");
//			        	File bufferedFile2 = new File(context.getCacheDir(),"play"+ (playe+1)+ ".dat");
//			        	if(!bufferedFile2.exists()){
//			        		isplay = false;
//			        	}
			        	File bufferedFile = new File(context.getCacheDir(),"play"+ (++playe)+ ".dat");
			        	System.out.println("文件的名字为-------------"+playe);
			        	if(bufferedFile.exists()){
			        		mediaPlayer = createMediaPlayer(bufferedFile);
			        		System.out.println(mediaPlayer.getDuration()+"------开始播放170---------------"+mediaPlayer.getCurrentPosition());
			        		mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
					    	mediaPlayer.start();
					    	isplay = false;
					    	try {
								Thread.sleep(120000);
								isplay = true;
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
    	
			        	}
			        	else{
			        		System.out.println("文件不存在----------------");
			        		isplay = false;
			        		try {
								Thread.sleep(10000);
								isplay = true;
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
			        	}
      	
				    	//startPlayProgressUpdater();    
				    
					//	playButton.setEnabled(true);
			        } catch (IOException e) {
			        	Log.e(getClass().getName(), "Error initializing the MediaPlayer.", e);
			        }   
			}
		}
	};
	 
}

我这个只是为了验证是否想法可行,因此第二段音乐是在2分钟以后才继续播放的

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 	xmlns:android="http://schemas.android.com/apk/res/android"
			    android:orientation="vertical"
			    android:layout_width="fill_parent"
			    android:layout_height="fill_parent"
			    android:padding="10px"
			    android:background="@drawable/back">

	<TextView  	android:id="@+id/text_kb_streamed"
				android:layout_width="fill_parent" 
			    android:layout_height="wrap_content" 
			    android:textStyle="bold"
	        	android:text="流媒体测试"/>
	
	    <Button	android:id="@+id/button_stream"
	        android:layout_width="wrap_content" 
	        android:layout_height="wrap_content"
		    android:layout_marginTop="10px"
            style="?android:attr/buttonStyleSmall" 
	        android:text="开始缓冲"/>

   <RelativeLayout
                android:layout_width="wrap_content"
			    android:layout_height="wrap_content" 
    >
		    	<SeekBar
    android:id="@+id/progress_bar" 
    android:layout_height="wrap_content"
    android:layout_width="200px"
    style="?android:attr/progressBarStyleHorizontal"
    />
      <TextView  
              android:id="@+id/playTime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/progress_bar"
            android:text="00:00"
    ></TextView>
 
</RelativeLayout>	
   <RelativeLayout
                android:layout_width="wrap_content"
			    android:layout_height="wrap_content" 
    >
    <ImageButton	android:id="@+id/button_play"
			        android:layout_width="wrap_content" 
			        android:layout_height="wrap_content"
		            android:layout_marginTop="5px"
		            style="?android:attr/buttonStyleSmall" 
		    		android:src="@drawable/button_pause"/>
</RelativeLayout>
</LinearLayout>

没有了,复制下来就能用

转载于:https://my.oschina.net/lhjtianji/blog/69211

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值