Audio playing one

Keywords: Android MediaPlayer xml

I. simple audio playing

[project preparation]

① a video file, the location of the video file ----- > create a new folder under res row ----- > put the video in the row folder

② generally speaking, audio playback does not need to stay in the interface all the time, so audio playback should be placed in the service, even if the interface is recycled, it is still playing.

 

[project structure]

[interface code]

1 <Button
2         android:id="@+id/btn_play"
3         android:text="play"
4         android:layout_width="match_parent"
5         android:layout_height="wrap_content" />

 

[MainActivity.class]

 1 public class MainActivity extends AppCompatActivity {
 2     
 3     ImageView ivPlay = null, ivRePlay = null;
 4     @Override
 5     protected void onCreate(Bundle savedInstanceState) {
 6         super.onCreate(savedInstanceState);
 7         setContentView(R.layout.activity_main);
 8 
 9         ivPlay = (ImageView) findViewById(R.id.btn_play);
10         ivPlay.setOnClickListener(new View.OnClickListener() {
11             @Override
12             public void onClick(View view) {
13                 Intent intent = new Intent(MainActivity.this, MediaPlayService.class);
14                 startService(intent)
15             }
16         });
17     }
18 }

[service code]

 1 public class MediaServiceA extends Service {
 2 
 3     MediaPlayer mediaPlayer;
 4     public MediaServiceA() {
 5     }
 6     @Override
 7     public IBinder onBind(Intent intent) {
 8         // TODO: Return the communication channel to the service.
 9         throw new UnsupportedOperationException("Not yet implemented");
10     }
11     
12     @Override
13     public int onStartCommand(Intent intent, int flags, int startId) {
14         
15         if (mediaPlayer==null) {
16             mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.ylzs);
17         }//Yes mediaPlayer Judge whether it is empty. If it is not empty, it will not be Create,Otherwise, it will repeat
18         if (mediaPlayer!=null) {
19             mediaPlayer.start();
20         }
21         return super.onStartCommand(intent, flags, startId);
22     }
23 }

[prompt] when creating a service, you can register it by the following methods. Otherwise, the service needs to register

[AndroidManifest.xml]

1 <service
2             android:name=".service.MediaServiceA"
3             android:enabled="true"
4             android:exported="true" />

 

[effect] the synthesizer will move after clicking

Posted by Stressed on Mon, 02 Dec 2019 10:33:27 -0800