展会信息港展会大全

android在线播放音乐 调用android自带的播放器 边下载边播放
来源:互联网   发布日期:2015-09-29 10:24:42   浏览:19544次  

导读:android在线音乐一种方法是调用android自带的播放器//调用系统自带播放器Intent intent = new Intent();Uri uri = Uri.parse(http://mul1.tximg.cn/music/group/bbs/mp3/44/100715/1279159638887.mp3?z=......

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 SeekBarprogressBar;

private TextView playTime;

private long mediaLengthInKb, mediaLengthInSeconds;

private int totalKbRead = 0;

private File downloadingMediaFile;

private Context context;

String url ;

int progress_leng;

private MediaPlayermediaPlayer;

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(Contextcontext, 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"?>

<LinearLayoutxmlns: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">

<TextViewandroid: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>

赞助本站

人工智能实验室

相关热词: 在线播放 音乐

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港