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 mainly introduces Android Studio how to achieve a music player, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
1. Project overview 1. Requirements analysis
Comprehensive use of UI interface design, data storage, Activity (activity), Service (service), MusicPlayer, ListView and other knowledge to design and develop a music player with music list.
2. Design and analysis
The entire project consists of five classes and five layout files:
Where frag1 and frag2 are java files
MusicActivity is an Activity file
MusicService is a Service file
MainActivity is the Activity file that is automatically generated when the project is created.
Activity_main is the layout file of MainActivity, showing the main interface when running APP.
Activity_music is the layout file of MusicActivity, which displays the music player interface.
Music_list and item_layout work together to form the layout file of frag1
This is the music list interface (open the APP default music list interface).
Frag2_layout is the layout file of frag2, which mainly displays the album cover image.
3. Resource file analysis
Create a raw folder under the res folder, put three music files, paste the music cover image bg.jpg and player background image music_bg.jpg in the drawable folder, and the btn_bg_selector.xml file of the background selector, as shown in the figure:
II. Development environment
III. Prepare tools
1. Choose several music files downloaded by yourself and name them music0, music1, music2, etc. Here the songs should be of mp3 type and the number is random. The subscript of the song name starts at 0, because the url address I set in the code starts at 0, otherwise it will flash.
2. Select the singer's picture corresponding to each song, cut it into a circle and save it, and name it music0, music1, music2 and so on.
The picture must be cut into a circle. The ellipse will affect the running effect and cause flicker. If you are not sure how to cut the picture into a circle, you can learn at the end of the article.
3. Prepare a background picture of the music player, name it music_bg, and then find another picture to use as an album picture, named bg.
Fourth, detailed design 1. Build the layout of the main interface.
First open Android Studio and create a new project, File-- > New-- > New Project-- > Empty Project, whose name is Music_List.
The name of the package is set at will. Here the blogger needs to modify the save path of the zj.dzh; project file. Do not put it on disk C. what the blogger chooses here is to put it in a Projects folder of disk E to form the good habit of putting the project under the English path.
Finally, choose API 18:Android 4.3, because it has 99.5% cross-platform (very good compatibility), because its version is very low, basically the simulator API version is higher than 20, so this software can run on a variety of other devices. Click Finish to complete the creation.
When designing an app, you must first design the layout file, and then design the java file, because the layout can be written on it. Let's take a look at the activity_main layout file, which mainly shows the main interface. What is the main interface is an interface that is displayed by default after APP is running.
The outermost layer uses the LinearLayout linear layout, and then sets the vertical arrangement. There are two small LinearLayout, the top TextView, the content setting is "I like", and then the second small LinearLayout puts two levels of TextView controls, showing "songs" and "albums".
All the remaining space at the bottom is given to Fragment, and its id is content. It doesn't matter if I don't know Fragment here. Anyway, I just know that it can display content just like TextView. The effect is as shown in the figure:
Fragment is a kind of UI fragment that can be embedded in the activity, which enables the program to make more reasonable and full use of the space of the large screen. The original intention is to adapt to the large screen tablet computer, which can be regarded as a small Activity, also known as Activity fragment.
The complete code is as follows:
Then go back to our Activity file. The MainActivity class is the main class of the whole project. First, create the control you need, then bind the control, and then set the listener. The bottom navigation bar sets two menu files: frag1 (song menu) and frag2 (album menu). The frag1 song menu is displayed by default, and click to switch to display the frag2 album menu. The code is as follows:
Package zj.dzh.music_list;import androidx.appcompat.app.AppCompatActivity;import androidx.fragment.app.FragmentManager;import androidx.fragment.app.FragmentTransaction;import android.os.Bundle;import android.view.View;import android.widget.TextView;public class MainActivity extends AppCompatActivity implements View.OnClickListener {/ / create the variable private TextView tv1,tv2; private FragmentManager fm; private FragmentTransaction ft of the control you need @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); / / bind control tv1= (TextView) findViewById (R.id.menu1); tv2= (TextView) findViewById (R.id.menu2); / / set listener, fixed tv1.setOnClickListener (this) Tv2.setOnClickListener (this); / / if inheriting FragmentActivity,fm=getFragmentManger (); fm=getSupportFragmentManager (); / / fm can be understood as the manager of Fragment display, and ft is its changer ft=fm.beginTransaction (); / / frag1 ft.replace is displayed by default (R.id.content new frag1 ()) / / submit the changed content ft.commit ();} @ Override / / the click event of the control public void onClick (View v) {ft=fm.beginTransaction (); / / switch tab switch (v.getId ()) {case R.id.menu1: ft.replace (R.id.content.new frag1 ()) Break; case R.id.menu2: ft.replace (R.id.contentMagneNew frag2 ()); break; default: break;} ft.commit ();}} 2, create service class 2.1, service overview
2.2. Service creation
To create a MusicService file, right-click the package name-- > New-- > Service-- > Service, as shown below:
Name it MusicService, and then Finish.
2.3. How to start the service
2.4. Lifecycle of services
MusicService Code:
Package zj.dzh.music_list;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.net.Uri;import android.os.Binder;import android.os.Bundle;import android.os.IBinder;import android.os.Message;import java.util.Timer;import java.util.TimerTask;// this is a Service service class public class MusicService extends Service {/ / declare a MediaPlayer reference private MediaPlayer player; / / declare a timer reference private Timer timer / / Constructor public MusicService () {} @ Override public IBinder onBind (Intent intent) {return new MusicControl ();} @ Override public void onCreate () {super.onCreate (); / / create music player object player=new MediaPlayer () } / / add timer to set the playback progress bar in the music player public void addTimer () {/ / if timer does not exist, that is, there is no reference to the instance if (timer==null) {/ / create timer object timer=new Timer () TimerTask task=new TimerTask () {@ Override public void run () {if (player==null) return; int duration=player.getDuration (); / obtain the total duration of the song int currentPosition=player.getCurrentPosition (); / / get the playback progress Message msg= MusicActivity.handler.obtainMessage () / / create a message object / / encapsulate the total duration and playback progress of music into bundle Bundle bundle=new Bundle (); bundle.putInt ("duration", duration); bundle.putInt ("currentPosition", currentPosition) / / encapsulate the bundle into the msg message object msg.setData (bundle); / / finally send the message to the message queue MusicActivity.handler.sendMessage (msg) of the main thread;}} / / 5 milliseconds after starting the timing task, execute the task task for the first time, and then execute timer.schedule (task,5500) every 500ms (0.5s) }} / / Binder is a cross-process communication method class MusicControl extends Binder {public void play (int I) {/ / String path Uri uri=Uri.parse ("android.resource://" + getPackageName () + "/ raw/" + "music" + I); try {/ / reset music player player.reset () / / load multimedia files player=MediaPlayer.create (getApplicationContext (), uri); player.start (); / / play music addTimer (); / / add timer} catch (Exception e) {e.printStackTrace () }} / / the following pause resume and exit methods all call the method public void pausePlay () {player.pause (); / / pause playing music} public void continuePlay () {player.start () that comes with MediaPlayer. / / continue playing music} public void seekTo (int progress) {player.seekTo (progress); / / set the playback position of music}} / / destroy the multimedia player @ Override public void onDestroy () {super.onDestroy (); if (player==null) return; if (player.isPlaying ()) player.stop () / / stop playing music player.release (); / / release the occupied resources player=null;//, set player to empty}} 3, set up the layout of the music playback interface
Right-click the package name, create a new Activity, name it MusicActivity, and click Finish, which will generate an activity_music file to display the music playback interface, as shown in the figure:
(1) MusicActivity class: controls the function of playing, pausing, continuing and exiting music through the onClick method. It binds and connects to MusicService. Displays the total duration of the song when the music is played, as well as the current playing time of the song, and controls the movement of the progress bar of the song. The code is as follows:
Package zj.dzh.music_list;import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity;import android.animation.ObjectAnimator;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Build;import android.os.Bundle;import android.os.Handler;import android.os.IBinder;import android.os.Message;import android.view.View;import android.view.animation.LinearInterpolator;import android.widget.ImageView;import android.widget.SeekBar;import android.widget.TextView Import static java.lang.Integer.parseInt;public class MusicActivity extends AppCompatActivity implements View.OnClickListener {/ / progress bar private static SeekBar sb; private static TextView tv_progress,tv_total,name_song; / / Animation private ObjectAnimator animator; private MusicService.MusicControl musicControl; private String name; private Intent intent1,intent2; private MyServiceConn conn; / / record whether the service is unbound. There is no private boolean isUnbind = false by default. @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_music); / / get the information from frag1 intent1=getIntent (); init ();} private void init () {/ / the position of the little green dot on the progress bar, that is, the current playback time tv_progress= (TextView) findViewById (R.id.tv_progress) / / the total length of the progress bar, that is, the total time tv_total= (TextView) findViewById (R.id.tv_total); / / the control of the progress bar sb= (SeekBar) findViewById (R.id.sb); / / the control of the song name display name_song= (TextView) findViewById (R.id.song_name) / / set click event listeners findViewById (R.id.btn_play) .setOnClickListener (this); findViewById (R.id.btn_pause) .setOnClickListener (this); findViewById (R.id.btn_continue_play) .setOnClickListener (this); findViewById (R.id.btn_exit) .setOnClickListener (this); name=intent1.getStringExtra ("name"); name_song.setText (name) while binding the control. / / create an intention object that jumps from the current Activity to Service intent2=new Intent (this,MusicService.class); conn=new MyServiceConn (); / / creates a service connection object bindService (intent2,conn,BIND_AUTO_CREATE) / / bind the service / / add event listeners to the slider. Sure enough, each control has a different click event method name sb.setOnSeekBarChangeListener (new SeekBar.OnSeekBarChangeListener () {/ / this line note is to ensure that the API is above KITKAT before the simulator can run smoothly. That is, @ RequiresApi (api = Build.VERSION_CODES.KITKAT) @ Override public void onProgressChanged (SeekBar seekBar, int progress, boolean fromUser) {/ / end the animation if (progress==seekBar.getMax ()) {animator.pause () when the slider reaches the end. / / stop playing animation} @ Override / / call public void onStartTrackingTouch (SeekBar seekBar) {} @ Override / / call public void onStopTrackingTouch (SeekBar seekBar) {when the slider stops sliding / / change the progress of music playback according to the progress of dragging int progress=seekBar.getProgress () / / get the progress of seekBar musicControl.seekTo (progress); / / change the playback progress}}); / / declare and bind the music player's iv_music control ImageView iv_music= (ImageView) findViewById (R.id.iv_music); String position= intent1.getStringExtra ("position") / / praseInt () is to change the string into an integer type int i=parseInt (position); iv_music.setImageResource (frag1.icons [I]); / / rotation and 0fjue 360.0f animate the rotation from 0 °to 360 °animator=ObjectAnimator.ofFloat (iv_music, "rotation", 0fjue 360.0f); animator.setDuration (10000) / / the animation rotation time is 10 seconds animator.setInterpolator (new LinearInterpolator ()); / / constant speed animator.setRepeatCount (- 1) / /-1 means to animate the infinite loop} / / handler mechanism, which can be understood as communication between threads. I get a piece of information and tell you about it. It's as simple as public static Handler handler=new Handler () {/ / create a message handler object / / process messages sent from child threads in the main thread @ Override public void handleMessage (Message msg) {Bundle bundle=msg.getData () / / get the music playback progress sent from the child thread / / get the current progress currentPosition and the total duration duration int duration=bundle.getInt ("duration"); int currentPosition=bundle.getInt ("currentPosition"); / / set sb.setMax (duration); sb.setProgress (currentPosition) to a pair of progress bars / / how many minutes and how many seconds is the song int minute=duration/1000/60; int second=duration/1000%60; String strMinute=null; String strSecond=null; if (minute
Item_layout: the item layout, which is used in combination with the above music_list list. It is equivalent to the layout of each row in the list. The layout effect is as shown in the figure:
The item_layout code is as follows:
5. Set up the layout of the album interface
Right-click the package name, New-- > Java Class, name it frag2, and click OK. As shown in the figure:
(1) frag2 category: display the cover album picture, click the album button in the main interface to jump to this interface. The code is as follows:
Package zj.dzh.music_list;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import androidx.fragment.app.Fragment;public class frag2 extends Fragment {/ / create a View private View zj; / / display layout public View onCreateView (final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {zj = inflater.inflate (R.layout.frag2_layout, null); return zj;}}
(2) create a new layout file and name it frag2_layout, as shown below:
Frag2_layout is used to set up an ImageView to display album images. The code is as follows:
Of course, frag2 is free to play, such as setting up singer profiles, MV lists or charts, and so on.
6. Import resource files
Create a new raw folder under the res folder and copy and paste the music files you just prepared into the raw folder. The corresponding cover circle image, background image and album image are copied and pasted into drawable, where the blogger only chooses three songs and three cover circle images, and there is no limit on the number of songs set by everyone.
Once again, pay attention to the naming; the mp3 song file opened in Android is garbled, do not worry, do not need to open it.
At this point, the complete music player project has been created.
Project effect 1. Create a simulator
Select your own simulator to run. If there is no simulator, click AVD and select New Simulator:
Select a version higher than API 21 to download, as shown in the figure:
2. Run the demo
(1) run the mobile phone simulator to display the main interface:
(2) Click the album tab:
(3) Select the song tab, select the first song "Lightyear away" and open it, jump to the music playback page, the singer's cover picture is displayed in the middle, and it is found that the title of the song "Lightyear away" has also been passed:
(4) Click the play music button, the music starts to play, the progress bar starts to slide, and the picture starts to rotate:
(5) Click the pause button, the music stops playing, the progress bar stops sliding, and the picture stops rotating:
(6) Click the continue play button, the music continues to play, and the singer's picture continues to rotate:
(7) Click the exit button to return to the main interface:
(8) choose the second song "Red High heels" and play it. Here, the progress bar can be dragged freely, and the song will be played to the corresponding position:
(9) choose the third song "Love Story" and play it:
The running effect and function are very complete, and so far the realization of the music player has been completed. friends who like it can do it by themselves and put on their favorite photos of Aidou and their favorite songs.
VI. Summary of the project
This music player project will enable you to master the basic technology of Android program development, including Android basic knowledge, UI interface, data storage, four major components, network programming, advanced programming and so on. Everyone's proficiency can be of great help to the future Android development.
Attach how to cut the picture into a circle
1. Copy the image to be cropped (a rectangular image with the same width and height) into the WPS document:
2. Click the cropping image option in the vertical toolbar on the right, as shown in the figure:
3. Select the ellipse option (the matrix image is cut out to be a circle), as shown in the figure:
4. Click the cropping option in the upper toolbar, and the image will be cropped into a circle:
5. Right-click the circular area, click Save as Picture, and save the picture to local use.
Thank you for reading this article carefully. I hope the article "how to implement a Music player in Android Studio" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
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.