0

我是android开发的新手。在我的应用程序中,我实现了一个音频播放器,它从 sd 卡播放声音。我希望它播放并仅显示我在应用程序工作区的文件夹中提供的那些音频文件的列表(就像我们在可绘制中提供的图像)这里是代码。先感谢您

播放.java

public class Play extends ListActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;

private MediaCursorAdapter mediaAdapter = null;
private TextView selelctedFile = null;
private SeekBar seekbar = null;
private MediaPlayer player = null;
private ImageButton playButton = null;
private ImageButton prevButton = null;
private ImageButton nextButton = null;

private boolean isStarted = true;
private String currentFile = "";
private boolean isMoveingSeekBar = false;

private final Handler handler = new Handler();

private final Runnable updatePositionRunnable = new Runnable() {
        public void run() {
                updatePosition();
        }
};

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);

selelctedFile = (TextView)findViewById(R.id.selectedfile);
seekbar = (SeekBar)findViewById(R.id.seekbar);
playButton = (ImageButton)findViewById(R.id.play);
prevButton = (ImageButton)findViewById(R.id.prev);
nextButton = (ImageButton)findViewById(R.id.next);

player = new MediaPlayer();

player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekbar.setOnSeekBarChangeListener(seekBarChanged);

Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);

if(null != cursor)
{
        cursor.moveToFirst();

        mediaAdapter = new MediaCursorAdapter(this, R.layout.list, cursor);

        setListAdapter(mediaAdapter);

        playButton.setOnClickListener(onButtonClick);
        nextButton.setOnClickListener(onButtonClick);
        prevButton.setOnClickListener(onButtonClick);
}
}

@Override
    protected void onListItemClick(ListView list, View view, int position, long id) {
        super.onListItemClick(list, view, position, id);

        currentFile = (String) view.getTag();

        startPlay(currentFile);
}

@Override
protected void onDestroy() {
        super.onDestroy();

        handler.removeCallbacks(updatePositionRunnable);
        player.stop();
        player.reset();
        player.release();

        player = null;
}

private void startPlay(String file) {
        Log.i("Selected: ", file);

        selelctedFile.setText(file);
        seekbar.setProgress(0);

        player.stop();
        player.reset();

        try {
                player.setDataSource(file);
                player.prepare();
                player.start();
        } catch (IllegalArgumentException e) {
                e.printStackTrace();
        } catch (IllegalStateException e) {
                e.printStackTrace();
        } catch (IOException e) {
                e.printStackTrace();
        }

        seekbar.setMax(player.getDuration());
        playButton.setImageResource(android.R.drawable.ic_media_pause);

        updatePosition();

        isStarted = true;
}

private void stopPlay() {
        player.stop();
        player.reset();
        playButton.setImageResource(android.R.drawable.ic_media_play);
        handler.removeCallbacks(updatePositionRunnable);
        seekbar.setProgress(0);

        isStarted = false;
}

private void updatePosition(){
        handler.removeCallbacks(updatePositionRunnable);

        seekbar.setProgress(player.getCurrentPosition());

        handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY);
}

private class MediaCursorAdapter extends SimpleCursorAdapter{

        public MediaCursorAdapter(Context context, int layout, Cursor c) {
                super(context, layout, c, 
                                new String[] { MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
                                new int[] { R.id.displayname, R.id.title, R.id.duration });
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
                TextView title = (TextView)view.findViewById(R.id.title);
                TextView name = (TextView)view.findViewById(R.id.displayname);
                TextView duration = (TextView)view.findViewById(R.id.duration);

                name.setText(cursor.getString(
                                cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));

                title.setText(cursor.getString(
                                cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));

                long durationInMs = Long.parseLong(cursor.getString(
                                cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));

                double durationInMin = ((double)durationInMs/1000.0)/60.0;

                durationInMin = new BigDecimal(Double.toString(durationInMin)).setScale(2, BigDecimal.ROUND_UP).doubleValue(); 

                duration.setText("" + durationInMin);

                view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
                LayoutInflater inflater = LayoutInflater.from(context);
                View v = inflater.inflate(R.layout.list, parent, false);

                bindView(v, context, cursor);

                return v;
        }
}

private View.OnClickListener onButtonClick = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
                switch(v.getId())
                {
                        case R.id.play:
                        {
                                if(player.isPlaying())
                                {
                                        handler.removeCallbacks(updatePositionRunnable);
                                        player.pause();
                                        playButton.setImageResource(android.R.drawable.ic_media_play);
                                }
                                else
                                {
                                        if(isStarted)
                                        {
                                                player.start();
                                                playButton.setImageResource(android.R.drawable.ic_media_pause);

                                                updatePosition();
                                        }
                                        else
                                        {
                                                startPlay(currentFile);
                                        }
                                }

                                break;
                        }
                        case R.id.next:
                        {
                                int seekto = player.getCurrentPosition() + STEP_VALUE;

                                if(seekto > player.getDuration())
                                        seekto = player.getDuration();

                                player.pause();
                                player.seekTo(seekto);
                                player.start();

                                break;
                        }
                        case R.id.prev:
                        {
                                int seekto = player.getCurrentPosition() - STEP_VALUE;

                                if(seekto < 0)
                                        seekto = 0;

                                player.pause();
                                player.seekTo(seekto);
                                player.start();

                                break;
                        }
                }
        }
};

private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
                stopPlay();
        }
};

private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {

        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
                // returning false will call the OnCompletionListener
                return false;
        }
};

private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
                isMoveingSeekBar = false;
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
                isMoveingSeekBar = true;
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
                if(isMoveingSeekBar)
                {
                        player.seekTo(progress);

                        Log.i("OnSeekBarChangeListener","onProgressChanged");
                }
        }
};
}

播放.xml

<?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">

    <ListView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@android:id/list"
        android:layout_weight="1.0"/>

    <LinearLayout
            android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@android:drawable/screen_background_light"
    android:padding="10dip">

    <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/selectedfile"
            android:text="Not file selected"
            android:textColor="@android:color/black"
            android:gravity="center_horizontal"
            android:singleLine="true"
            android:ellipsize="middle"/>

    <SeekBar
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/seekbar"
            android:max="100"
            android:paddingBottom="10dip"/>

    <LinearLayout
                    android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:background="@android:drawable/screen_background_light">

            <ImageButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/prev"
                    android:src="@android:drawable/ic_media_previous"/>

            <ImageButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/play"
                    android:src="@android:drawable/ic_media_play"/>

            <ImageButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/next"
                    android:src="@android:drawable/ic_media_next"/>

    </LinearLayout> 
    </LinearLayout>

4

1 回答 1

0

您需要将音乐放到 assets 目录(即创建名为“sounds”的子文件夹),然后按方法列出它的内容:

myContext.getAssets().list(”sounds");

然后您必须将资产附加到 MediaPlayer 对象:

mediaPlayer.setDataSource(myContext.getAssets().openFd(soundPathInAssets));

您还应该看到这个线程(因为我提供给您的那段代码会播放整个目录):Play audio file from the assets directory

编辑:示例项目中的代码(如果删除我的保管箱上的文件):

MainActivity.java

public class MainActivity extends Activity {
    MediaPlayer mMediaPlayer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ListView list = (ListView) findViewById(R.id.listView1);
        mMediaPlayer = new MediaPlayer();
        Button playPause = (Button) findViewById(R.id.play);
        playPause.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mControl.isPlaying()){
                    mControl.pause();
                } else {
                    mControl.start();
                }
            }
        });
        try {
            list.setAdapter(new MyAdapter(getAssets().list("music")));
        } catch (IOException e) {
            e.printStackTrace();
        }
        list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                String path = (String) list.getAdapter().getItem(position);
                try {
                    AssetFileDescriptor fd = getAssets().openFd("music/"+path);
                    mMediaPlayer.reset();
                    mMediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
                    mMediaPlayer.prepare();
                    mMediaPlayer.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    class MyAdapter extends BaseAdapter {

        private String[] content;

        public MyAdapter(String[] content){
            this.content=content;
        }

        @Override
        public int getCount() {
            return content.length;
        }

        @Override
        public Object getItem(int position) {
            return content[position];
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView==null){
                convertView = new TextView(getApplicationContext());
                TextView cv = (TextView) convertView;
                cv.setTextSize(18);
                cv.setPadding(8, 8, 8, 8);
            }
            TextView v = (TextView) convertView;
            v.setText(content[position]);
            return v;
        }
    }
    MediaPlayerControl mControl = new MediaPlayerControl() {

        public void start() {
            mMediaPlayer.start();
        }

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

        public int getDuration() {
            return mMediaPlayer.getDuration();
        }

        public int getCurrentPosition() {
            return mMediaPlayer.getCurrentPosition();
        }

        public void seekTo(int i) {
            mMediaPlayer.seekTo(i);
        }

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

        public int getBufferPercentage() {
            return 0;
        }

        public boolean canPause() {
            return true;
        }

        public boolean canSeekBackward() {
            return true;
        }

        public boolean canSeekForward() {
            return true;
        }
    };
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical">
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
   <Button
        android:id="@+id/play"
        android:background="@drawable/btn_transparent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="PlayPause" />
</LinearLayout>
于 2013-07-02T23:08:36.620 回答