现在的位置: 首页 > 综合 > 正文

【audio play音频】 android 简单的MP3播放器代码

2017年12月05日 ⁄ 综合 ⁄ 共 6016字 ⁄ 字号 评论关闭

一下简单的MP3播放器代码示例,实现的功能很简单大致是:
1:通过ContentResolver查询到手机中的MP3歌曲信息
2:通过一个Listview显示列表,
3:用一个服务播放歌曲
4:通过手势向左,向右滑动来控件前一曲,后一曲,并停止播放控件
由于代码没有多大的复杂性,笔者就没有详细的注解,直接上代码:
K_musicActivity.java

public class K_musicActivity extends Activity implements OnTouchListener,
                OnGestureListener {

        private LinearLayout m_LinearLayout;
        private ListView m_ListView;
        private Intent i;
        private Cursor cur;
        private GestureDetector mGestureDetector;
        private static final int FLING_MIN_DISTANCE = 50;
        private static final int FLING_MIN_VELOCITY = 100;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                
                // UI The bottommost LinearLayout  
                m_LinearLayout = new LinearLayout(this);
                //  Set up internal elements arranged  
                m_LinearLayout.setOrientation(LinearLayout.VERTICAL);
                //  Background color  
                m_LinearLayout.setBackgroundColor(Color.GREEN);
                
                // listView Storage of list of songs  
                m_ListView = new ListView(this);
                
                //  Sets the listView element layout parameters  
                LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                                LinearLayout.LayoutParams.FILL_PARENT,
                                LinearLayout.LayoutParams.WRAP_CONTENT);
                m_ListView.setBackgroundColor(Color.BLUE);
                m_LinearLayout.addView(m_ListView, param);
                
                //  This activity of the ContentView set to m  _LinearLayout
                this.setContentView(m_LinearLayout);
                
                //  Query the media information  
                cur = this.getContentResolver().query(
                                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                                MediaStore.Audio.Media.DEFAULT_SORT_ORDER);

                this.startManagingCursor(cur);
                
                //  歌典的信息通过一个列表添加到 ListView中  
                ListAdapter adapter = new SimpleCursorAdapter(this,
                                android.R.layout.simple_expandable_list_item_2, cur,
                                new String[] { MediaStore.Audio.Media.TITLE,
                                                MediaStore.Audio.Media.ARTIST }, new int[] {
                                                android.R.id.text1, android.R.id.text2 });
                m_ListView.setAdapter(adapter);
                
                //  To play a song Service, this is an Action path  
                i = new Intent("com.kennan.music");               
                //  Add click single songs to listen, to choose to play the song  
                m_ListView.setOnItemClickListener(clictlistener);
                
                //  Gestures detectors for a gesture capture, playback, implement stop playing  
                mGestureDetector = new GestureDetector(this);
                
                //  Add a touch of listening, and implementation of gestures  
                m_LinearLayout.setLongClickable(true);
                m_LinearLayout.setOnTouchListener(this);
                m_ListView.setLongClickable(true);
                m_ListView.setOnTouchListener(this);

        }       
        /**
         *  Click on a single song listening, and choose to play the song  
         */
        private AdapterView.OnItemClickListener clictlistener = new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                long arg3) {
                        
                        //  The song information moves the cursor to be click Department songs  
                        cur.moveToPosition(position);
                        //  Gets the URI of the song  
                        String data = cur.getString(cur
                                        .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                        //  The legend of the songs to the URI of the Service to play a song  
                        i.putExtra("data", data);

                }
        };       
        @Override
        public boolean onTouch(View v, MotionEvent event) {
                // OnGestureListener will analyzes the given motion event
                return mGestureDetector.onTouchEvent(event);
        }    
        /**
         *  Sliding events, to the right activities began playing the song, to the left to play to stop playing the song  
         */
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                        float velocityY) {
                //  Parameters:  
                // e1 ACTION: 1st  _DOWN MotionEvent
                // e2 : The last ACTION  _MOVE MotionEvent
                // velocityX : The x axis of movement speed, pixel  / Seconds  
                // velocityY : Y movement speed, pixel  / Seconds  

                //  The trigger conditions:  
                // X The coordinate of the displacement of the shaft is greater than the FLING  _MIN_DISTANCE And move faster than FLING  _MIN_VELOCITY Pixels  / Seconds  

                if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
                                && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
                        // Fling left
                        K_musicActivity.this.stopService(i);
                } else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
                                && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
                        // Fling right
                        
                        //  Close the currently playing service  , Avoid multiple service simultaneously play  
                        K_musicActivity.this.stopService(i);
                        K_musicActivity.this.startService(i);
                }

                return false;
        }
            
        //  Touch the touchscreen user, 1 MotionEvent ACTION  _DOWN Trigger  
        @Override
        public boolean onDown(MotionEvent e) {
                return false;
        }
        //  Touch the touchscreen user, has not yet been released or drag from a 1 MotionEvent ACTION  _DOWN Trigger  
        //  Note and onDown  () The difference, to emphasize that there is no release or drag status  
        @Override
        public void onShowPress(MotionEvent e) {
                // TODO Auto-generated method stub
        }
        //  User (touch screen) release, consists of a 1 MotionEvent ACTION  _UP Trigger  
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
                // TODO Auto-generated method stub
                return false;
        }

        //  User long by touch screen, consists of multiple MotionEvent ACTION  _DOWN Trigger  
        @Override
        public void onLongPress(MotionEvent e) {
                // TODO Auto-generated method stub

        }
        //  The user presses the touch screen, and drag ACTION by 1 MotionEvent  _DOWN,  Multiple ACTION  _MOVE Trigger  
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
                        float distanceY) {
                // TODO Auto-generated method stub
                return false;
        }

}
KMusicService.java服务类
public class KMusicService extends Service {
        private MediaPlayer player;
        public IBinder onBind(Intent arg0) {
                return null;
        }
        public void onStart(Intent intent, int startId) {
                super.onStart(intent, startId);               
                //  Get songs from a from URI activity  
                String uri = intent.getStringExtra("data");               
                player = new MediaPlayer();
                try {
                        player.setDataSource(uri);
                        player.prepare();
                } 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();
                }                
                player.start();
        }       
        public Service getService(){
                return this;
        }
        public void onDestroy() {
                player.stop();
                super.onDestroy();
        }
}

 

 

项目功能配置文件AndroidManifest.xml 

< ?xml version="1.0" encoding="utf-8"?>
< manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.kennan.k_music"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".K_musicActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    <service android:name="KMusicService">
        <intent-filter>
                                <action android:name="com.kennan.music" />
                                <category android:name="android.intent.category.DEFAULT" />
                </intent-filter>
    </service>
< /application>
    <uses-sdk android:minSdkVersion="7" />
< /manifest> 

 

抱歉!评论已关闭.