从android中的url播放mp3文件

时间:2015-03-22 10:01:38

标签: java android

我正在做什么:我正在尝试从Android中的网址播放mp3文件。并通过进度条控制其位置。

正在发生的事情:

对于strings.xml以下代码正常播放歌曲正在播放,我可以使用进度条定位进度

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Android mp3 player</string>
 <string name="testsong_20_sec">http://users.skynet.be/fa046054/home/P22/track06.mp3</string>

对于strings.xml以下代码,代码无法正常工作,我的意思是歌曲正在播放,但我无法使用进度条控制位置。唯一不同的是这个mp3文件是在谷歌驱动器。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Android mp3 player</string>

     <string name="testsong_20_sec">https://286898c83aa5e6a4f7b29cdbef3b2f54430b4e71.googledrive.com/host/0B6a-NfRKFX8HQVZRSzFON1ExZEE/Chadh%20Gayi%20Maa%20Tere%20Naam%20Ki%20Sherewali%20Ka%20Sancha.mp3</string>
 </resources>

我在寻找什么:如何确保我的代码播放正确的音乐,我可以使用第二个网址中的进度条正确切换

StreamingMp3Player.java

public class StreamingMp3Player extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{

    private ImageButton buttonPlayPause;
    private SeekBar seekBarProgress;
    public EditText editTextSongURL;

    private MediaPlayer mediaPlayer;
    private int mediaFileLengthInMilliseconds; // this value contains the song duration in milliseconds. Look at getDuration() method in MediaPlayer class

    private final Handler handler = new Handler();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initView();
    }

    /** This method initialise all the views in project*/
    private void initView() {
        buttonPlayPause = (ImageButton)findViewById(R.id.ButtonTestPlayPause);
        buttonPlayPause.setOnClickListener(this);

        seekBarProgress = (SeekBar)findViewById(R.id.SeekBarTestPlay);  
        seekBarProgress.setMax(99); // It means 100% .0-99
        seekBarProgress.setOnTouchListener(this);
        editTextSongURL = (EditText)findViewById(R.id.EditTextSongURL);
        editTextSongURL.setText(R.string.testsong_20_sec);

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnBufferingUpdateListener(this);
        mediaPlayer.setOnCompletionListener(this);
    }

    /** Method which updates the SeekBar primary progress by current song playing position*/
    private void primarySeekBarProgressUpdater() {
        seekBarProgress.setProgress((int)(((float)mediaPlayer.getCurrentPosition()/mediaFileLengthInMilliseconds)*100)); // This math construction give a percentage of "was playing"/"song length"
        if (mediaPlayer.isPlaying()) {
            Runnable notification = new Runnable() {
                public void run() {
                    primarySeekBarProgressUpdater();
                }
            };
            handler.postDelayed(notification,1000);
        }
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.ButtonTestPlayPause){
             /** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
            try {
                mediaPlayer.setDataSource(editTextSongURL.getText().toString()); // setup song from http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source
                mediaPlayer.prepare(); // you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer. 
            } catch (Exception e) {
                e.printStackTrace();
            }

            mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the song length in milliseconds from URL

            if(!mediaPlayer.isPlaying()){
                mediaPlayer.start();
                buttonPlayPause.setImageResource(R.drawable.button_pause);
            }else {
                mediaPlayer.pause();
                buttonPlayPause.setImageResource(R.drawable.button_play);
            }

            primarySeekBarProgressUpdater();
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(v.getId() == R.id.SeekBarTestPlay){
            /** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar primary progress position*/
            if(mediaPlayer.isPlaying()){
                SeekBar sb = (SeekBar)v;
                int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
                mediaPlayer.seekTo(playPositionInMillisecconds);
            }
        }
        return false;
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
         /** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
        buttonPlayPause.setImageResource(R.drawable.button_play);
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        /** Method which updates the SeekBar secondary progress by current song loading from URL position*/
        seekBarProgress.setSecondaryProgress(percent);
    }
}

main.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/widget31"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <EditText
        android:id="@+id/EditTextSongURL"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:height="100dp"
        android:lines="3"
        android:maxLines="3"
        android:minLines="1" >

        <requestFocus />

        <requestFocus />
    </EditText>

    <ImageButton
        android:id="@+id/ButtonTestPlayPause"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/EditTextSongURL"
        android:layout_centerHorizontal="true"
        android:contentDescription="TestPlayPause"
        android:onClick="onClick"
        android:src="@drawable/button_play" />

    <SeekBar
        android:id="@+id/SeekBarTestPlay"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/ButtonTestPlayPause" />

</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

这是因为谷歌驱动器HTTP服务器没有返回正确的文件长度。

$ wget -S https://286898c83aa5e6a4f7b29cdbef3b2f54430b4e71.googledrive.com/host/0B6a-NfRKFX8HQVZRSzFON1ExZEE/Chadh%20Gayi%20Maa%20Tere%20Naam%20Ki%20Sherewali%20Ka%20Sancha.mp3 ... Length: unspecified [audio/mpeg]

您没有总流长度,因此您没有相对于总长度的位置。运气不好。