4

視覚化(/sdcard/Musicのスキャン、プレイリストへの追加、再生と視覚化)を備えたシンプルな音楽プレーヤーを書きたいのですが、アプリを起動するとエラーが発生しますCannot start activity (ru.vspr.MyMediaPlayerActivity) java.lang.IllegalStateException 。どうすれば修正できますか?


ソースコード: http://www.mediafire.com/download/y1paremphr57mbz/MyMediaPlayer.zip


ログ:

    07-24 13:20:01.023 E/AndroidRuntime(22997): FATAL EXCEPTION: main
07-24 13:20:01.023 E/AndroidRuntime(22997): java.lang.RuntimeException: Unable to start activity ComponentInfo{ru.vspr/ru.vspr.MyMediaPlayerActivity}: java.lang.IllegalStateException
07-24 13:20:01.023 E/AndroidRuntime(22997): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
07-24 13:20:01.023 E/AndroidRuntime(22997): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
07-24 13:20:01.023 E/AndroidRuntime(22997): at android.app.ActivityThread.access$600(ActivityThread.java:123)
07-24 13:20:01.023 E/AndroidRuntime(22997): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
07-24 13:20:01.023 E/AndroidRuntime(22997): at android.os.Handler.dispatchMessage(Handler.java:99)
07-24 13:20:01.023 E/AndroidRuntime(22997): at android.os.Looper.loop(Looper.java:137)
07-24 13:20:01.023 E/AndroidRuntime(22997): at android.app.ActivityThread.main(ActivityThread.java:4424)
07-24 13:20:01.023 E/AndroidRuntime(22997): at java.lang.reflect.Method.invokeNative(Native Method)
07-24 13:20:01.023 E/AndroidRuntime(22997): at java.lang.reflect.Method.invoke(Method.java:511)
07-24 13:20:01.023 E/AndroidRuntime(22997): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-24 13:20:01.023 E/AndroidRuntime(22997): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-24 13:20:01.023 E/AndroidRuntime(22997): at dalvik.system.NativeStart.main(Native Method)
07-24 13:20:01.023 E/AndroidRuntime(22997): Caused by: java.lang.IllegalStateException
07-24 13:20:01.023 E/AndroidRuntime(22997): at android.media.MediaPlayer._reset(Native Method)
07-24 13:20:01.023 E/AndroidRuntime(22997): at android.media.MediaPlayer.reset(MediaPlayer.java:1218)
07-24 13:20:01.023 E/AndroidRuntime(22997): at ru.vspr.MyMediaPlayerActivity.loadMusic(MyMediaPlayerActivity.java:156)
07-24 13:20:01.023 E/AndroidRuntime(22997): at ru.vspr.MyMediaPlayerActivity.loadTrack(MyMediaPlayerActivity.java:147)
07-24 13:20:01.023 E/AndroidRuntime(22997): at ru.vspr.MyMediaPlayerActivity.initialize(MyMediaPlayerActivity.java:100)
07-24 13:20:01.023 E/AndroidRuntime(22997): at ru.vspr.MyMediaPlayerActivity.onCreate(MyMediaPlayerActivity.java:58)
07-24 13:20:01.023 E/AndroidRuntime(22997): at android.app.Activity.performCreate(Activity.java:4492)
07-24 13:20:01.023 E/AndroidRuntime(22997): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
07-24 13:20:01.023 E/AndroidRuntime(22997): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
07-24 13:20:01.023 E/AndroidRuntime(22997): ... 11 more

package ru.vspr;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.media.audiofx.Visualizer;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.util.Log;

public class MyMediaPlayerActivity extends Activity implements OnCompletionListener {
    WakeLock wakeLock;
    private static final String[] EXTENSIONS = { ".mp3", ".wav", ".ogg" }; //Воспроизводимые форматы
    List<String> trackNames; //Названия воспроизводимых треков
    List<String> trackArtworks; //Обложки воспроизводимых треков
    File path; //Директория, откуда будет загружена музыка
    File path2; //Директория, откуда будут загружены обложки треков
    Button btnPlay; //Эта кнопка будет менять своё изображение при нажатии
    Random random; //Рспользовано для случайного воспроизведения
    boolean shuffle; //Случайное воспроизведение включено?
    boolean isTuning; 
    int currentTrack; //Рндекс текущего трека
    MediaPlayer mediaPlayer; //Плеер
    Visualizer mVisualizer; //Визуализатор для него
    VisualizerView mVisualizerView; //View для визуализатора

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
//      PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
//      wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "Powered by YOBA Engine");
        setContentView(R.layout.main); 
        initialize();
    }

    @Override
    public void onResume(){
        super.onResume();
        wakeLock.acquire();
    }

    @Override
    public void onPause(){
        super.onPause();
        wakeLock.release();
        if(mediaPlayer != null){
            if(isPlaying()){
                pause();
                isTuning = false;
                btnPlay.setBackgroundResource(R.drawable.play);
            }
            if(isFinishing()){
                dispose();
                finish();
            }
        } else{
            if(isFinishing()){
                finish();
            }
        }
    }

    private void initialize(){
        btnPlay = (Button) findViewById(R.id.btnPlay);
        btnPlay.setBackgroundResource(R.drawable.play);
        trackNames = new ArrayList<String>();
        trackArtworks = new ArrayList<String>();
        currentTrack = 0;
        shuffle = false;
        isTuning = false;
        random = new Random();
        mediaPlayer = new MediaPlayer();

        addTracks(getTracks());
        loadTrack();
    }

    //Generate a String Array that represents all of the files found
    private String[] getTracks(){
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) 
                    || Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)){
                path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
                path2 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                String[] temp = path.list();
                return temp;
            } else{
                Toast.makeText(getBaseContext(), "SD Card is either mounted elsewhere or is unusable", Toast.LENGTH_LONG).show();
            }
        return null;
    }

    //Adds the playable files to the trackNames List
    private void addTracks(String[] temp){
        if(temp != null){
            for(int i = 0; i < temp.length; i++){
                //Only accept files that have one of the extensions in the EXTENSIONS array
                if(trackChecker(temp[i])){
                    trackNames.add(temp[i]);
                    trackArtworks.add(temp[i].substring(0, temp[i].length()-4));
                }
            }
            Toast.makeText(getBaseContext(), "Loaded " + Integer.toString(trackNames.size()) + " Tracks", Toast.LENGTH_SHORT).show();
        }
    }

    //Checks to make sure that the track to be loaded has a correct extenson
    private boolean trackChecker(String trackToTest){
        for(int j = 0; j < EXTENSIONS.length; j++){
            if(trackToTest.contains(EXTENSIONS[j])){
                return true;
            }
        }
        return false;
    }

    //Loads the track by calling loadMusic
    private void loadTrack(){
        if(mediaPlayer != null){
            dispose();
        }
        if(trackNames.size() > 0){
            loadMusic();
        }
    }

    //loads a Music instance using either a built in asset or an external resource
    private void loadMusic(){
            try{
                FileInputStream fis = new FileInputStream(new File(path, trackNames.get(currentTrack)));
                FileDescriptor fileDescriptor = fis.getFD();
                mediaPlayer.setDataSource(fileDescriptor);
                mediaPlayer.prepare();
                mediaPlayer.setOnCompletionListener(this);              
//              setupVisualizerFxAndUI();               
            } catch(IOException e){
                e.printStackTrace();
                Toast.makeText(getBaseContext(), "Error Loading " + trackNames.get(currentTrack), Toast.LENGTH_LONG).show();
            }
//          return null;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        super.onCreateOptionsMenu(menu);
        createMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch(item.getItemId()){
        case 0:
            //Set Looping
            synchronized(this){
                if(isLooping()){
                    setLooping(false);
                    Toast.makeText(getBaseContext(), "Playing Tracks Sequentially", Toast.LENGTH_SHORT).show();
                } else{
                    setLooping(true);
                    Toast.makeText(getBaseContext(), "Looping " + trackNames.get(currentTrack), Toast.LENGTH_SHORT).show();
                }
            }
            return true;
        case 1:
            //Set Shuffle
            synchronized(this){
                if(shuffle){
                    setShuffle(false);
                } else{
                    setShuffle(true);
                }
            }
            return true;
        case 2:
            //Stop Music
            synchronized(this){
                switchTracks();
                btnPlay.setBackgroundResource(R.drawable.play);
            }
            return true;
        default:
            return false;
        }
    }

    private void createMenu(Menu menu){
        MenuItem miLooping = menu.add(0, 0, 0, "Looping");{
            miLooping.setIcon(R.drawable.looping);
        }
        MenuItem miShuffle = menu.add(0, 1, 1, "Shuffle");{
            miShuffle.setIcon(R.drawable.shuffle);
        }
        MenuItem miStop = menu.add(0, 2, 2, "Stop");{
            miStop.setIcon(R.drawable.stop);
        }
    }

    public void click(View view){
        int id = view.getId();
        switch(id){
        case R.id.btnPlay:
            synchronized(this){
                if(isTuning){
                    isTuning = false;
                    btnPlay.setBackgroundResource(R.drawable.play);
                    pause();
                } else{
                    isTuning = true;
                    btnPlay.setBackgroundResource(R.drawable.pause);
                    playTrack();
                }
            }
            return;
        case R.id.btnPrevious:
            setTrack(0);
            loadTrack();
            playTrack();
            return;
        case R.id.btnNext:
            setTrack(1);
            loadTrack();
            playTrack();
            return;
        default:
            return;
        }
    }

    private void setTrack(int direction){
        if(direction == 0){
            currentTrack--;
            if(currentTrack < 0){
                currentTrack = trackNames.size()-1;
            }
        } else if(direction == 1){
            currentTrack++;
            if(currentTrack > trackNames.size()-1){
                currentTrack = 0;
            }
        }
        if(shuffle){
            int temp = random.nextInt(trackNames.size());
            while(true){
                if(temp != currentTrack){
                    currentTrack = temp;
                    break;
                }
                temp++;
                if(temp > trackNames.size()-1){
                    temp = 0;
                }
            }
        }
    }

    //Plays the Track
    private void playTrack(){
        if(isTuning && mediaPlayer != null){
            play();
            Toast.makeText(getBaseContext(), "Playing " + trackNames.get(currentTrack).substring(0, trackNames.get(currentTrack).length()-4), Toast.LENGTH_SHORT).show();
        }
    }

    //Simply sets shuffle to isShuffle and then displays a message for confirmation
    private void setShuffle(boolean isShuffle) {
        shuffle = isShuffle;
        if(shuffle){
            Toast.makeText(getBaseContext(), "Shuffle On", Toast.LENGTH_SHORT).show();
        } else{
            Toast.makeText(getBaseContext(), "Shuffle Off", Toast.LENGTH_SHORT).show();
        }
    }
    public void onCompletion(MediaPlayer mediaPlayer) {
        synchronized(this){

        }
    }

    public void play() {
        if(mediaPlayer.isPlaying()){
            return;
        }
        try{
            synchronized(this){
                mediaPlayer.start();
            }
        } catch(IllegalStateException ex){
            ex.printStackTrace();
    }
    }

    public void stop() {
        mediaPlayer.stop();
        synchronized(this){

        }
    }

    public void switchTracks(){
        mediaPlayer.seekTo(0);
        mediaPlayer.pause();
    }

    public void pause() {
        mediaPlayer.pause();
    }

    public boolean isPlaying() {
        return mediaPlayer.isPlaying();
    }

    public boolean isLooping() {
        return mediaPlayer.isLooping();
    }

    public void setLooping(boolean isLooping) {
        mediaPlayer.setLooping(isLooping);
    }

    public void setVolume(float volumeLeft, float volumeRight) {
        mediaPlayer.setVolume(volumeLeft, volumeRight);
    }

    public void dispose() {
        if(mediaPlayer.isPlaying()){
            stop();
        }
        mediaPlayer.release();
    }

    public void setupVisualizerFxAndUI() {
                mVisualizerView = new VisualizerView(this);
                mVisualizerView = (VisualizerView) findViewById(R.id.visualizerView);
                mVisualizer = new Visualizer(mediaPlayer.getAudioSessionId());
                mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
                mVisualizer.setDataCaptureListener(new Visualizer.OnDataCaptureListener() {
                        public void onWaveFormDataCapture(Visualizer visualizer, byte[] bytes,
                                                          int samplingRate) {
                            mVisualizerView.updateVisualizer(bytes);
                        }

                        public void onFftDataCapture(Visualizer visualizer, byte[] bytes, int samplingRate) {}
                    }, Visualizer.getMaxCaptureRate() / 1, true, false);
    }

}

PSこのエラーが発生する前に、「再生」ボタンを押すと音は出ますが、視覚化されません。これを修正する方法はありますか?

PPS私の英語でごめんなさい、お願いします

4

1 に答える 1

1

java.lang.IllegalStateException

VM が正しい状態にないときにアクションが試行されるとスローされます。

http://developer.android.com/reference/java/lang/IllegalStateException.html

07-24 12:49:27.054 E/AndroidRuntime(21733): Caused by: java.lang.IllegalStateException 07-24 12:49:27.054 E/AndroidRuntime(21733): at android.media.MediaPlayer.setDataSource(Native Method) 07-24 12:49:27.054 E/AndroidRuntime(21733): at android.media.MediaPlayer.setDataSource(MediaPlayer.java:889)

アイドル状態に戻すには、reset() を呼び出す必要があります。そうして初めて setDataSource() を呼び出すことができます

編集:

コードの残りの部分をonCompletion

public void onCompletion(MediaPlayer mediaPlayer) {

        try {

            mediaPlayer.reset();
            mediaPlayer.setDataSource(path.getAbsolutePath());

            mediaPlayer.prepare();

            mediaPlayer.setOnCompletionListener(this);

            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
于 2013-07-24T09:01:44.497 に答える