一、簡單的音頻播放 【項目準備】 ①一個視頻文件,視頻文件的位置 >在res下新建文件夾row >將視頻放入row文件夾中 ②一般音頻播放是不需要一直停留在界面的,所以音頻播放應該放在service中,即使界面被回收,也一直在播放。 【項目結構】 【界面代碼】 【MainActivity.class ...
一、簡單的音頻播放
【項目準備】
①一個視頻文件,視頻文件的位置---->在res下新建文件夾row------>將視頻放入row文件夾中
②一般音頻播放是不需要一直停留在界面的,所以音頻播放應該放在service中,即使界面被回收,也一直在播放。
【項目結構】
【界面代碼】
1 <Button
2 android:id="@+id/btn_play"
3 android:text="播放"
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代碼】
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 }//對mediaPlayer是否為空進行一個判斷,如果不為空就不再Create,否則會重覆播放
18 if (mediaPlayer!=null) {
19 mediaPlayer.start();
20 }
21 return super.onStartCommand(intent, flags, startId);
22 }
23 }
【提示】創建service時可通過以下方法註冊,否則Service要進行註冊
【AndroidManifest.xml】
1 <service
2 android:name=".service.MediaServiceA"
3 android:enabled="true"
4 android:exported="true" />
【效果】點擊後合成器會在動