In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail how to quickly complete a simple music player in Android. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Realization process
Import music files, icons, backgrounds, etc., required by the project
1. Create a raw folder and import the music files into this folder so that we can use it in the project.
two。 Import the required pictures and icons in drawable
Design UI interface
1. Design 5 button controls, corresponding to the previous song, the next song, pause, play, exit
two。 Design three TextView, corresponding to the introduction of the song, the progress of the song (the total time of the song and the current playing time of the song), and the name of the song
Writing service Services
Create a MusicService object that inherits Service
Member variables required by MusicService
MyReceiver serviceReceiver;Thread processThread;AssetManager am;// is the attachment manager, which is used to find the location of the file according to the file name and open the file String [] musics = new String [] {"legendsneverdie.mp3", "promise.mp3", "beautiful.mp3"}; / / the current status of the song information displayed by default is MediaPlayer mPlayer;//, which is not played by 0x11; 0x12 is being played 0x13 stands for pausing int status = 0x11scrambling / recording the music currently playing int current = 0
Realize circular playback
Public void onCreate () {super.onCreate (); am = getAssets (); / / create BroadcastReceiver serviceReceiver = new MyReceiver (); / / create IntentFilter IntentFilter filter = new IntentFilter (); filter.addAction (MainActivity.CTL_ACTION); registerReceiver (serviceReceiver, filter); / / create MediaPlayer mPlayer = new MediaPlayer () / / bind listeners mPlayer.setOnCompletionListener (new OnCompletionListener () {@ Override public void onCompletion (MediaPlayer mp) {Log.d ("musicService", "playback completed") for MediaPlayer playback completion event; current++; if (current > = 3) {current = 0 } / / prepare and play music prepareAndPlay (musics [current]); / / send broadcast notification Activity change text box Intent sendIntent = new Intent (MainActivity.UPDATE_ACTION); sendIntent.putExtra ("current", current); sendIntent.putExtra ("currentTime", mPlayer.getCurrentPosition ()) SendIntent.putExtra ("totalTime", mPlayer.getDuration ()); / / send a broadcast that will be received by the BroadcastReceiver in the Activity component to sendBroadcast (sendIntent);}}); private void prepareAndPlay (String music) {try {/ / Open the specified music file AssetFileDescriptor afd = am.openFd (music) MPlayer.reset (); / / loads the specified sound file using MediaPlayer. MPlayer.setDataSource (afd.getFileDescriptor (), afd.getStartOffset (), afd.getLength ()); / / prepare sound mPlayer.prepare (); / / play mPlayer.start ();} catch (IOException e) {e.printStackTrace ();}}
Implement refresh progress bar
ProcessThread = new Thread (new Runnable () {@ Override public void run () {while (true) {if (status = = 0x12) {try {Thread.sleep (1000); Intent sendIntent = new Intent (MainActivity.UPDATE_ACTION)) SendIntent.putExtra ("current", current); sendIntent.putExtra ("currentTime", mPlayer.getCurrentPosition ()); sendIntent.putExtra ("totalTime", mPlayer.getDuration ()); / / send a broadcast that will be received by the sendBroadcast (sendIntent) by the BroadcastReceiver in the Activity component } catch (InterruptedException e) {e.printStackTrace ();}}); processThread.start ();}
Implementation of broadcast communication receiver (for communication with activity)
Public class MyReceiver extends BroadcastReceiver {@ Override public void onReceive (final Context context, Intent intent) {int control= intent.getIntExtra ("control",-1); Log.d ("musicReceiver", "received broadcast, control=" + control) Switch (control) {/ / play or pause case 1: / originally in no playback state if (status = = 0x11) {/ / prepare and play music prepareAndPlay (music [current]); status = 0x12 } / / originally in playback state else if (status = = 0x12) {/ / paused mPlayer.pause (); / / changed to paused state status = 0x13 } / / originally paused else if (status = = 0x13) {/ / playback mPlayer.start (); / / change state status = 0x12;} break / / next case 2: if (status = = 0x12 | | status = = 0x13) {mPlayer.stop (); if (current+ 1 > = musics.length) {current = 0;} else {current++ } prepareAndPlay (musics [current]); status = 0x12; break;} / / the previous song case 3: if (status = = 0x12 | | status = = 0x13) {mPlayer.stop () If (current-1)
< 0) { current = musics.length - 1; } else { current--; } prepareAndPlay(musics[current]); status = 0x12; } } // 广播通知Activity更改图标、文本框 Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION); sendIntent.putExtra("update", status); sendIntent.putExtra("current", current); // 发送广播,将被Activity组件中的BroadcastReceiver接收到 sendBroadcast(sendIntent); }} activity的实现 初始化和动态绑定接收器 // 获取界面中显示歌曲标题、作者文本框TextView title, author, currentTime, totalTime;// 播放/暂停、停止按钮ImageButton play;ImageView lastMusic, nextMusic;// 进度条ProgressBar progressBar;ActivityReceiver activityReceiver;public static final String CTL_ACTION = "org.xr.action.CTL_ACTION";public static final String UPDATE_ACTION = "org.xr.action.UPDATE_ACTION";// 定义音乐的播放状态,0x11代表没有播放;0x12代表正在播放;0x13代表暂停int status = 0x11;String[] titleStrs = new String[]{"Legends Never Die", "约定", "美丽新世界"};String[] authorStrs = new String[]{"英雄联盟", "周蕙", "伍佰"};@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // 获取程序界面界面中的两个按钮 play = (ImageButton) this.findViewById(R.id.play); lastMusic = this.findViewById(R.id.lastMusic); nextMusic = this.findViewById(R.id.nextMusic); title = (TextView) findViewById(R.id.title); author = (TextView) findViewById(R.id.author); currentTime = findViewById(R.id.currentTime); totalTime = findViewById(R.id.totalTime); progressBar = findViewById(R.id.progressBar); // 为两个按钮的单击事件添加监听器 play.setOnClickListener(this); lastMusic.setOnClickListener(this); nextMusic.setOnClickListener(this); activityReceiver = new ActivityReceiver(); // 创建IntentFilter IntentFilter filter = new IntentFilter(); // 指定BroadcastReceiver监听的Action filter.addAction(UPDATE_ACTION); // 注册BroadcastReceiver registerReceiver(activityReceiver, filter); Intent intent = new Intent(this, MusicService.class); // 启动后台Service startService(intent);} 设置activity的广播接收器(接收service发送过来的广播) public void onReceive(Context context, Intent intent) { // 获取Intent中的update消息,update代表播放状态 int update = intent.getIntExtra("update", -1); // 获取Intent中的current消息,current代表当前正在播放的歌曲 int current = intent.getIntExtra("current", -1); int totalPosition = intent.getIntExtra("totalTime", -1); int currentPosition = intent.getIntExtra("currentTime", -1); Log.d("activityReceiver", "收到广播"); Log.d("activityReceiver", "current:" + current + " totalPosition:" + totalPosition + " currentPosition:" + currentPosition + " update:" + update); if (current >= 0) {title.setText (titleStrings [current]); author.setText (authorizations [current]);} if (totalPosition > = 0) {SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("mm:ss", Locale.CHINA); Date date = new Date (totalPosition); String formatTime = simpleDateFormat.format (current); totalTime.setText (formatTime) } if (currentPosition > = 0) {double process = ((double) currentPosition/totalPosition) * 100; Log.d ("activityReceiver", "current progress:" + (double) currentPosition/totalPosition); SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("mm:ss", Locale.CHINA); Date date = new Date (currentPosition); String formatTime = simpleDateFormat.format (date); progressBar.setProgress (int) process) CurrentTime.setText (formatTime);} switch (update) {case 0x11: play.setImageResource (R.drawable.play); status = 0x11; break; / / Control system enters the playback state case 0x12: / / set to use the pause icon play.setImageResource (R.drawable.pause) in the playback state / / set current state status = 0x12; break; / / Control system enters pause state case 0x13: / / set to use playback icon play.setImageResource (R.drawable.play) in paused state; / / set current state status = 0x13; break }}
Realize the click function of the icon
/ / create Intent Intent intent = new Intent ("org.xr.action.CTL_ACTION"); switch (source.getId ()) {/ / Press the play / pause button case R.id.play: intent.putExtra ("control", 1); break; case R.id.lastMusic: intent.putExtra ("control", 3) Case R.id.nextMusic: intent.putExtra ("control", 2);} / / send a broadcast that will be received by the BroadcastReceiver in the Service component sendBroadcast (intent) } this is the end of the article on "how to quickly complete a simple music player in Android". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.