android在線播放音樂

jopen 12年前發布 | 59K 次閱讀 Android 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>
 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!