扫描SD卡,显示歌曲信息,简单播放MP3,层层低级掌握服务.............

一,在主线程直接完成这一切,app退出,歌曲不播放了....(掌握contentResolver读取media信息和播放mp3)


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

package china.playsong;

import android.app.ListActivity;

import android.content.ContentResolver;

import android.database.Cursor;

import android.media.MediaPlayer;

import android.os.Bundle;

import android.provider.MediaStore;

import android.util.Log;

import android.view.View;

import android.widget.AdapterView;

import android.widget.Toast;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

public class MainActivity extends ListActivity implements AdapterView.OnItemClickListener {

    private ContentResolver resolver;

    private List<Bean> datas;

    private MediaPlayer player;

    private int currPlay = 0;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        initView();

        setListAdapter(new MyAdapter(datas, this));

        getListView().setOnItemClickListener(this);

    }

    private void initView() {

        resolver = getContentResolver();

        datas = new ArrayList<Bean>();

        getDataFromPrivoder();

        player = new MediaPlayer();

        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override

            public void onCompletion(MediaPlayer mediaPlayer) {

                //自动播放下一曲

                currPlay = currPlay + 1;

                if (currPlay < datas.size()) {

                    //如果不是最后一曲

                    String pathNext = datas.get(currPlay).getPath();

                    palySong(pathNext);

                } else {

                    //如果是最后一曲,则归零

                    currPlay = 0;

                    String pathZore = datas.get(0).getPath();

                    palySong(pathZore);

                }

            }

        });

    }

    private void getDataFromPrivoder() {

        //过滤其他信息,只取MP3

        Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, "MIME_TYPE=?", new String[]{"audio/mpeg"}, null);

        //有时候参数设置错误,可能导致cursor的为空,所以加一个判断

        if (cursor.getCount() != 0) {

            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));

                String songName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));

                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));

                String size = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE)) + "";

                //加入数据

                datas.add(new Bean(title, songName, path, size));

            }

        } else {

            //提示为空

            Log.i("ddd", "cursor is empty,please check!");

            Toast.makeText(MainActivity.this, "cursor数据为空,请检查参数!", Toast.LENGTH_SHORT).show();

        }

    }

    @Override

    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

        //当前点击的位置传给全局变量

        currPlay = position;

        //播放歌曲

        palySong(datas.get(position).getPath());

    }

    public void palySong(String path) {

        try {

            //检查清空

            if (player.isPlaying()) {

                player.stop();

            }

            //因为在主线程,所以把播放的歌曲信息显示在当前屏幕第上面

            getListView().setSelection(currPlay);

            player.reset();

            player.setDataSource(path);

            player.prepare();

            player.start();

            //歌曲播放完之后,进入onCompleteListener

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    @Override

    protected void onDestroy() {

        if (player.isPlaying()) {

            player.stop();

        }

        player.release();

        super.onDestroy();

    }

}

?其他的Adapter就是简单的继承baseAdapter的,item的layout就是四个textView;


二,过度到用Server播放,这里简单满足一下功能,(退出app后,继续后台播放,这下面没有添加在界面停止服务的功能,需要在应用程序中停止......  )这里仅仅是应用一下service

这里的MainActivity只是获取一下数据,添加点击监听,打开服务....


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

package china.playsongbyservice;

import android.content.ContentResolver;

import android.content.Intent;

import android.database.Cursor;

import android.provider.MediaStore;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.AdapterView;

import android.widget.ListView;

import android.widget.Toast;

import java.util.ArrayList;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView listView;

    private List<Bean> lists;

    private ContentResolver resolver;

    protected static List<String> paths;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        initView();

    }

    private void initView() {

        listView = (ListView) findViewById(R.id.listView);

        lists = new ArrayList<Bean>();

        //把path的路径集中,方便读取,因为这次service不与主线程互相通信

        paths = new ArrayList<String>();

        resolver =getContentResolver();

        getDatas();

        listView.setAdapter(new DemoAdapter(this, lists));

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override

            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                

                //打开服务

                Intent intent = new Intent(MainActivity.this,PlayService.class);

                intent.putExtra("pos", i);

                intent.putExtra("path", lists.get(i).getPath());

                startService(intent);

            }

        });

    }

    

    //获取数据.....

    private void getDatas() {

        Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, "MIME_TYPE=?", new String[]{"audio/mpeg"}, null);

        if (cursor.getCount() != 0) {

            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

                String mtitle = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));

                String mName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));

                String mType = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.MIME_TYPE));

                String mPath = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));

                lists.add(new Bean(mtitle, mName, mType, mPath));

            }

        } else {

            //提示为空

            Log.i("ddd", "cursor is empty,please check!");

            Toast.makeText(MainActivity.this, "cursor数据为空,请检查参数!", Toast.LENGTH_SHORT).show();

        }

        if (lists != null) {

            for (int i = 0; i < lists.size(); i++) {

                paths.add(lists.get(i).getPath());

            }

        }

    }

}

再写一个继承Service的类,基本是第一种主线程的移花接木


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

package china.playsongbyservice;

import android.app.Service;

import android.content.Intent;

import android.media.MediaPlayer;

import android.os.IBinder;

import android.support.annotation.Nullable;

import java.io.IOException;

/**

 * Created by Anonymous on 2016/2/24.

 */

public class PlayService extends Service {

    private MediaPlayer player;

    private int currentPos;

    @Override

    public void onCreate() {

        super.onCreate();

        player = new MediaPlayer();

        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override

            public void onCompletion(MediaPlayer mediaPlayer) {

                //自动下一曲

                currentPos = currentPos + 1;

                if (currentPos < MainActivity.paths.size()) {

                    String playNext = MainActivity.paths.get(currentPos);

                    playSong(playNext);

                } else {

                    currentPos = 0;

                    String playZero = MainActivity.paths.get(0);

                    playSong(playZero);

                }

            }

        });

    }

    @Nullable

    @Override

    public IBinder onBind(Intent intent) {

        return null;

    }

    @Override

    public int onStartCommand(Intent intent, int flags, int startId) {

        //      在这里赋值

        String playPath = intent.getStringExtra("path");

        currentPos = intent.getIntExtra("pos", 0);

        playSong(playPath);

        return super.onStartCommand(intent, flags, startId);

    }

    @Override

    public void onDestroy() {

        if (player != null) {

            player.stop();

            player.release();

        }

        super.onDestroy();

    }

    public void playSong(String str) {

        try {

            if (player.isPlaying()) {

                player.stop();

            }

            player.reset();

            player.setDataSource(str);

            player.prepare();

            player.start();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}



?

来自为知笔记(Wiz)

时间: 2024-10-19 08:45:02

扫描SD卡,显示歌曲信息,简单播放MP3,层层低级掌握服务.............的相关文章

Android - 通过系统数据库获取SD卡音乐媒体信息

当写一些东西(比如音乐播放器)的时候,就需要SD卡的mp3列表了-开始我是使用列文件来着,但是再获取文件的信息(歌手,专辑,图片,时长等..)很麻烦,所以直接用这个函数了- 1 private void getMusicPaths(){ 2 // 3 // 获取音乐列表 4 // 5 Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, M

手动通知扫描SD卡主动生成缩略图

最近做项目遇到的难题,调用系统拍照获取不到缩略图,非得关机重启才会生成,所以我们要主动通知系统扫描SD卡生成缩略图, 在Android4.4之前也就是以发送一个Action为“Intent.ACTION_MEDIA_MOUNTED”的广播通知执行扫描.如下: this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDire

Android4.4中拒绝发送Intent.ACTION_MEDIA_MOUNTED扫描SD卡的广播

通常在我们的项目中,可能会遇到写本地文件,最常用的就是图片文件,在这之后需要通知系统重新扫描SD卡,在Android4.4之前也就是以发送一个Action为"Intent.ACTION_MEDIA_MOUNTED"的广播通知执行扫描.如下: this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDir

Android中播放本地SD卡中歌曲需要的添加的权限

使用MediaPlayer播放本地Mp3文件时,需要注意的访问路径的问题以及访问权限的问题. 1.访问路径:/storage/emulated/0 此路径即为手机的根路径,可以通过下载ES文件浏览器软件查看当前播放的Mp3具体的路径,通过Environment.getExternalStorageDirectory().getPath()获取/storage/emulated/0这个SdCard路径这在组织 void android.media.MediaPlayer.setDataSource

18 手动发广播扫描sd卡

1 public void systemScan(){ 2 sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse( "file://" 3 + Environment.getExternalStorageDirectory()))); 4 } 全盘扫描

捕获异常、存sd卡、封装请求头体、加密map值、网络工具类、生成Json、Https协议、传log日志到服务器、app崩溃友好重启

点击打开链接,免积分下载 在集成了统计SDK(友盟统计,百度统计等)之后,有一个非常有利于测试的功能:错误分析!此功能能够将程序在运行中碰到的崩溃(runtimeException)问题反馈到服务器,帮助开发者改善产品,多适配机器.然而在公司android开发中不集成这些SDK,那应该怎么实现这样的功能呢?下面让我们来看下如何使用UncaughtExceptionHandler来捕获异常. 在Android开发中,常常会出现uncheched Exception 导致程序的crash,为了提供良

第36章 SDIO—SD卡读写测试

第36章     SDIO-SD卡读写测试 全套200集视频教程和1000页PDF教程请到秉火论坛下载:www.firebbs.cn 野火视频教程优酷观看网址:http://i.youku.com/firege 本章参考资料:<STM32F4xx参考手册>.<STM32F4xx规格书>.库帮助文档<stm32f4xx_dsp_stdperiph_lib_um.chm>以及SD简易规格文件<Physical Layer Simplified Specificatio

Android4.4中不能发送SD卡就绪广播

当在Android上进行图片的扫描功能开发时一般会使用:sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse(“file://”+ Environment.getExternalStorageDirectory()+ picPath)));的广播. 但是在Android4.4及以上版本中,执行上面的代码出现异常:W/ActivityManager( 498): Permission Denial: not allowed

RT-Thread 学习笔记(九)---开启基于SD卡中的 Elm FatFS 文件系统

软件环境:Win7,Keil MDK 4.72a, IAR EWARM 7.2, GCC 4.2,Python 2.7 ,SCons 2.3.2 硬件环境:Armfly STM32F103ZE-EK v3.0开发板 参考文章:RT-Thread编程指南 由于SD卡可插拔的便捷性,使得其在嵌入式中的应用中广泛使用. [1]修改底层驱动接口 (1)打开Armfly STM32F103ZE-EK v3.0开发板找到SD卡硬件接口部分,如下图: 从硬件接口可以看到,SD是SDIO的接口类型,amobbs