Thứ Năm, 25 tháng 10, 2018

Android - MediaPlayer

Android cung cấp nhiều cách để kiểm soát phát lại các tệp và luồng âm thanh / video. Một trong những cách này là thông qua một lớp gọi là MediaPlayer .

Android đang cung cấp lớp MediaPlayer để truy cập các dịch vụ mediaplayer tích hợp như phát âm thanh, video v.v. Để sử dụng MediaPlayer, chúng ta phải gọi phương thức tĩnh create () của lớp này. Phương thức này trả về một thể hiện của lớp MediaPlayer. Cú pháp của nó như sau:

MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);

Tham số thứ hai là tên của bài hát mà bạn muốn chơi. Bạn phải tạo một thư mục mới trong dự án của bạn với tên thô và đặt tệp nhạc vào đó.

Khi bạn đã tạo đối tượng Mediaplayer, bạn có thể gọi một số phương thức để bắt đầu hoặc dừng nhạc. Những phương pháp này được liệt kê dưới đây.
mediaPlayer.start();
mediaPlayer.pause();
Trên phương thức call to start () , nhạc sẽ bắt đầu phát từ đầu. Nếu phương thức này được gọi lại sau phương thức pause () , nhạc sẽ bắt đầu phát từ nơi nó bị bỏ lại và không phải từ đầu.

Để bắt đầu âm nhạc ngay từ đầu, bạn phải gọi phương thức reset () . Cú pháp của nó được đưa ra dưới đây.

mediaPlayer.reset();

Ngoài phương thức khởi động và tạm dừng, còn có các phương thức khác do lớp này cung cấp để xử lý tốt hơn các tệp âm thanh / video. Những phương pháp này được liệt kê dưới đây

Sr.NoPhương pháp & mô tả
1đang chơi()

Phương thức này chỉ trả về true / false cho biết bài hát đang phát hay không
2seekTo (vị trí)

Phương thức này lấy một số nguyên và di chuyển bài hát đến vị trí cụ thể đó mili giây
3getCurrentPosition ()

Phương thức này trả về vị trí hiện tại của bài hát theo mili giây
4getDuration ()

Phương thức này trả về tổng thời lượng của bài hát theo mili giây
5cài lại()

Phương pháp này đặt lại trình phát phương tiện
6giải phóng()
Phương thức này phát hành bất kỳ tài nguyên nào được gắn với đối tượng MediaPlayer
7setVolume (float leftVolume, float rightVolume)

Phương pháp này đặt âm lượng lên cho trình phát này
số 8setDataSource (FileDescriptor fd)

Phương thức này đặt nguồn dữ liệu của tệp âm thanh / video
9selectTrack (chỉ mục int)

Phương thức này lấy một số nguyên và chọn bản nhạc từ danh sách trên chỉ mục cụ thể đó
10getTrackInfo ()
Phương thức này trả về một mảng thông tin bản nhạc

Thí dụ

Đây là một ví dụ minh họa việc sử dụng lớp MediaPlayer. Nó tạo ra một trình phát phương tiện cơ bản cho phép bạn chuyển tiếp, lùi, phát và tạm dừng một bài hát.

Để thử nghiệm với ví dụ này, bạn cần chạy ứng dụng này trên thiết bị thực để nghe âm thanh.

Link đăng lý Học lập trình Android : Học lập trình Android cơ bản.

Các bướcSự miêu tả
1Bạn sẽ sử dụng Android studio IDE để tạo ứng dụng Android theo gói com.example.sairamkrishna.myapplication.
2Sửa đổi tệp src / MainActivity.java để thêm mã MediaPlayer.
3Sửa đổi res / layout / activity_main để thêm các thành phần XML tương ứng
4Tạo một thư mục mới dưới MediaPlayer với tên nguyên và đặt một tệp nhạc mp3 trong đó với tên là song.mp3
5Chạy ứng dụng và chọn thiết bị Android đang chạy và cài đặt ứng dụng trên đó và xác minh kết quả
Sau đây là nội dung của tệp hoạt động chính đã sửa đổi src / MainActivity.java .
package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;


public class MainActivity extends Activity {
   private Button b1,b2,b3,b4;
   private ImageView iv;
   private MediaPlayer mediaPlayer;
 
   private double startTime = 0;
   private double finalTime = 0;
 
   private Handler myHandler = new Handler();;
   private int forwardTime = 5000;
   private int backwardTime = 5000;
   private SeekBar seekbar;
   private TextView tx1,tx2,tx3;

   public static int oneTimeOnly = 0;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      b1 = (Button) findViewById(R.id.button);
      b2 = (Button) findViewById(R.id.button2);
      b3 = (Button)findViewById(R.id.button3);
      b4 = (Button)findViewById(R.id.button4);
      iv = (ImageView)findViewById(R.id.imageView);

      tx1 = (TextView)findViewById(R.id.textView2);
      tx2 = (TextView)findViewById(R.id.textView3);
      tx3 = (TextView)findViewById(R.id.textView4);
      tx3.setText("Song.mp3");

      mediaPlayer = MediaPlayer.create(this, R.raw.song);
      seekbar = (SeekBar)findViewById(R.id.seekBar);
      seekbar.setClickable(false);
      b2.setEnabled(false);

      b3.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Playing 
               sound",Toast.LENGTH_SHORT).show();
            mediaPlayer.start();

            finalTime = mediaPlayer.getDuration();
            startTime = mediaPlayer.getCurrentPosition();

            if (oneTimeOnly == 0) {
               seekbar.setMax((int) finalTime);
               oneTimeOnly = 1;
            }
    
            tx2.setText(String.format("%d min, %d sec",
               TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
               TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
               TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) 
                  finalTime)))
            );

            tx1.setText(String.format("%d min, %d sec",
               TimeUnit.MILLISECONDS.toMinutes((long) startTime),
               TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
               TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) 
                  startTime)))
            );

            seekbar.setProgress((int)startTime);
            myHandler.postDelayed(UpdateSongTime,100);
            b2.setEnabled(true);
            b3.setEnabled(false);
         }
      });

      b2.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Pausing 
               sound",Toast.LENGTH_SHORT).show();
            mediaPlayer.pause();
            b2.setEnabled(false);
            b3.setEnabled(true);
         }
      });

      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            int temp = (int)startTime;

            if((temp+forwardTime)<=finalTime){
               startTime = startTime + forwardTime;
               mediaPlayer.seekTo((int) startTime);
               Toast.makeText(getApplicationContext(),"You have Jumped forward 5 
                  seconds",Toast.LENGTH_SHORT).show();
            }else{
               Toast.makeText(getApplicationContext(),"Cannot jump forward 5
                  seconds",Toast.LENGTH_SHORT).show();
            }
         }
      });

      b4.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            int temp = (int)startTime;

            if((temp-backwardTime)>0){
               startTime = startTime - backwardTime;
               mediaPlayer.seekTo((int) startTime);
               Toast.makeText(getApplicationContext(),"You have Jumped backward 5 
                  seconds",Toast.LENGTH_SHORT).show();
            }else{
               Toast.makeText(getApplicationContext(),"Cannot jump backward 5 
                  seconds",Toast.LENGTH_SHORT).show();
            }
         }
      });
   }

   private Runnable UpdateSongTime = new Runnable() {
      public void run() {
         startTime = mediaPlayer.getCurrentPosition();
         tx1.setText(String.format("%d min, %d sec",
            TimeUnit.MILLISECONDS.toMinutes((long) startTime),
            TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
            toMinutes((long) startTime)))
         );
         seekbar.setProgress((int)startTime);
         myHandler.postDelayed(this, 100);
      }
   };
}
Sau đây là nội dung sửa đổi của xml res / layout / activity_main.xml .
Trong đoạn mã dưới đây abc cho biết logo của tutorialspoint.com
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" 
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

   <TextView android:text="Music Palyer" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />

   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:src="@drawable/abc"/>

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/forward"
      android:id="@+id/button"
      android:layout_alignParentBottom="true"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/pause"
      android:id="@+id/button2"
      android:layout_alignParentBottom="true"
      android:layout_alignLeft="@+id/imageView"
      android:layout_alignStart="@+id/imageView" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/back"
      android:id="@+id/button3"
      android:layout_alignTop="@+id/button2"
      android:layout_toRightOf="@+id/button2"
      android:layout_toEndOf="@+id/button2" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/rewind"
      android:id="@+id/button4"
      android:layout_alignTop="@+id/button3"
      android:layout_toRightOf="@+id/button3"
      android:layout_toEndOf="@+id/button3" />

   <SeekBar
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/seekBar"
      android:layout_alignLeft="@+id/textview"
      android:layout_alignStart="@+id/textview"
      android:layout_alignRight="@+id/textview"
      android:layout_alignEnd="@+id/textview"
      android:layout_above="@+id/button" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceSmall"
      android:text="Small Text"
      android:id="@+id/textView2"
      android:layout_above="@+id/seekBar"
      android:layout_toLeftOf="@+id/textView"
      android:layout_toStartOf="@+id/textView" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceSmall"
      android:text="Small Text"
      android:id="@+id/textView3"
      android:layout_above="@+id/seekBar"
      android:layout_alignRight="@+id/button4"
      android:layout_alignEnd="@+id/button4" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceMedium"
      android:text="Medium Text"
      android:id="@+id/textView4"
      android:layout_alignBaseline="@+id/textView2"
      android:layout_alignBottom="@+id/textView2"
      android:layout_centerHorizontal="true" />

</RelativeLayout>
Sau đây là nội dung của res / values ​​/ string.xml .
<resources>
   <string name="app_name">My Application</string>
   <string name="back"><![CDATA[<]]></string>
   <string name="rewind"><![CDATA[<<]]></string>
   <string name="forward"><![CDATA[>>]]></string>
   <string name="pause">||</string>
</resources>
Sau đây là nội dung của tệp AndroidManifest.xml .
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.sairamkrishna.myapplication.MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>

Hãy thử chạy ứng dụng của bạn. Tôi cho rằng bạn đã kết nối thiết bị Android Mobile thực tế với máy tính của mình.

Để chạy ứng dụng từ Eclipse, mở một trong các tệp hoạt động của dự án của bạn và nhấp vào biểu tượng Chạy từ thanh công cụ. 

Trước khi bắt đầu ứng dụng của bạn, Android studio sẽ hiển thị các màn hình sau đây
Học lập trình Android cơ bản
Theo mặc định, bạn sẽ thấy nút tạm dừng bị tắt. Bây giờ nhấn nút play và nó sẽ trở thành vô hiệu hóa và tạm dừng nút trở thành kích hoạt. Nó được thể hiện trong hình dưới đây

Cho đến bây giờ, âm nhạc đã được chơi. Bây giờ nhấn nút tạm dừng và xem thông báo tạm dừng. Điều này được hiển thị bên dưới

Bây giờ khi bạn nhấn nút phát một lần nữa, bài hát sẽ không phát từ đầu nhưng từ nơi nó bị tạm dừng. Bây giờ nhấn nhanh nút tua đi hoặc lùi để nhảy bài hát về phía trước hoặc lùi 5 giây. Một thời gian đến khi bài hát không thể nhảy về phía trước. Tại thời điểm này, thông báo sẽ xuất hiện sẽ giống như thế này

Âm nhạc của bạn sẽ vẫn phát trong nền trong khi bạn đang thực hiện các tác vụ khác trong điện thoại di động của mình. Để ngăn chặn nó, bạn phải thoát khỏi ứng dụng này từ các hoạt động nền.

Không có nhận xét nào:

Đăng nhận xét

Lập trình Android - RenderScript

Trong chương này, chúng ta sẽ tìm hiểu về Android RenderScript. Thông thường các ứng dụng trên Android được thiết kế để tiêu thụ tài nguyên ...