0

我正在尝试创建一个示例 MP3 播放器。问题是,当我单击将从 url 播放 mp3 的按钮时,它会在模拟器中显示这个 logcat 并且歌曲根本不播放,当我在 Samsung Galaxy y duos lite (2.3.6) 中运行它时,当我按下播放按钮时,什么也没有发生(手机已连接到互联网),所以我尝试使用资源作为资产文件夹(2.34 MB)中的本机文件运行应用程序。同样的问题仍然存在。

import java.io.IOException;
import java.net.URL;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
    MediaPlayer mediaPlayer = new MediaPlayer();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }public void music(View v) throws IOException
{ final String url = "http://xxx.xxx.xxx/1.mp3";
    AssetFileDescriptor afd = getAssets().openFd("1.mp3");
    //final MediaPlayer mediaPlayer = new MediaPlayer();
    try{
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setDataSource(url);
   //mediaPlayer.setDataSource(afd.getFileDescriptor());
    mediaPlayer.prepareAsync();
    mediaPlayer.start();    
}
    catch(Exception e) {
        e.printStackTrace(); }}
@Override
protected void onPause() {
   super.onPause();
    mediaPlayer.stop();  //>>> stop myMediaPlayer
    mediaPlayer.release(); //>>> free myMediaPlayer
  }
private void releaseMediaPlayer() {
    if (mediaPlayer != null) {
        if(mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.release();
        mediaPlayer = null;
    }
}
@Override
protected void onDestroy() {
    super.onDestroy();
    mediaPlayer.stop();  //>>> stop myMediaPlayer
    mediaPlayer.release(); //>>> free myMediaPlayer
    releaseMediaPlayer();
  }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    }

这是当我单击触发音乐方法的播放按钮时出现的 Logcat 条目。

08-04 13:31:11.179: W/System.err(28943): java.lang.IllegalStateException
08-04 13:31:11.195: W/System.err(28943):    at android.media.MediaPlayer.setAudioStreamType(Native Method)
08-04 13:31:11.195: W/System.err(28943):    at com.example.music.MainActivity.music(MainActivity.java:30)
08-04 13:31:11.195: W/System.err(28943):    at java.lang.reflect.Method.invokeNative(Native Method)
08-04 13:31:11.195: W/System.err(28943):    at java.lang.reflect.Method.invoke(Method.java:507)
08-04 13:31:11.195: W/System.err(28943):    at android.view.View$1.onClick(View.java:2139)
08-04 13:31:11.195: W/System.err(28943):    at android.view.View.performClick(View.java:2485)
08-04 13:31:11.195: W/System.err(28943):    at android.view.View$PerformClick.run(View.java:9080)
08-04 13:31:11.195: W/System.err(28943):    at android.os.Handler.handleCallback(Handler.java:587)
08-04 13:31:11.195: W/System.err(28943):    at android.os.Handler.dispatchMessage(Handler.java:92)
08-04 13:31:11.195: W/System.err(28943):    at android.os.Looper.loop(Looper.java:130)
08-04 13:31:11.195: W/System.err(28943):    at android.app.ActivityThread.main(ActivityThread.java:3687)
08-04 13:31:11.203: W/System.err(28943):    at java.lang.reflect.Method.invokeNative(Native Method)
08-04 13:31:11.203: W/System.err(28943):    at java.lang.reflect.Method.invoke(Method.java:507)
08-04 13:31:11.203: W/System.err(28943):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
08-04 13:31:11.203: W/System.err(28943):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-04 13:31:11.203: W/System.err(28943):    at dalvik.system.NativeStart.main(Native Method)

PS我也使用了访问Internet的权限。

感谢你的协助。

4

1 回答 1

0

试试这个例子:

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;


@SuppressLint({ "NewApi", "DefaultLocale" })
public class Detail extends Activity  implements OnClickListener, OnTouchListener, 
                                OnCompletionListener, OnBufferingUpdateListener{
    String url;
    String nameFile;
    String name;
    boolean isBack = false;
    private ImageButton buttonPlayPause;
    private SeekBar seekBarProgress;

    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();
    private ltv.model.MSong mSong;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail);    

        // FOR PLAY MP3 FILE
        url = "mp3 link";
        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);

        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(url);
                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);
    }   

    @Override
    public void onBackPressed() {
        if (isBack) {
            super.onBackPressed();
        } else {
            if (mediaPlayer != null) {
                if (mediaPlayer.isPlaying()) {
                    back();
                } else {
                    super.onBackPressed();
                }
            } else {
                super.onBackPressed();
            }
        }
    }   

}
于 2013-08-04T09:57:26.497 回答