Здравствуйте, сегодня будем создавать ещё один вариант медиаплеера.
Скачать исходники для статьи можно ниже
О предыдущих вариантах медиоплееров можно прочитать тут:
1. Android Studio: Создаем простой аудиоплеер (AudioPlayer)
2. Android Studio: Создаем аудиоплеер со шкалой времени (AudioPlayer)
Начало аналогичное – как и по предыдущим статям о создании аудиоплеера:
1. Создаем новый проект в Android Studio:
Я выбрал платформу Android 4.0 – для того чтобы наше будущее приложение запускалось на версиях Андроида – Android 4.0+
Выбираем шаблон Empty Activity (Пустое Активити):
Далее оставляем все по умолчанию:
И жмем на кнопку Finish.
2. Создаем следующие файлы:
Также нам потребуется картинка яблока и песня в формате mp3:
– mp3 файл песни можно скачать здесь;
– картинку яблока можно скачать здесь.
2.1. Код файла MainActivity
package mnogoblog.ru.mediapleer3;
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(),"Пауза 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 sec",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);
}
};
}
2.2. Код файла activity_main.xml
<?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">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
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"
android:textAlignment="center" />
<TextView android:text="Music Palyer" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textAlignment="center" />
<ImageView
android:layout_width="match_parent"
android:layout_height="226dp"
android:id="@+id/imageView"
android:layout_below="@+id/textView"
android:src="@drawable/abc"
android:layout_above="@+id/textView4"
android:layout_alignRight="@+id/textView4"
android:layout_alignEnd="@+id/textView4"
android:textAlignment="center" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="63dp"
android:layout_alignParentBottom="true"
android:gravity="bottom">
<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_weight="1" />
<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_alignTop="@+id/textView2"
android:layout_toRightOf="@+id/textView2"
android:layout_toEndOf="@+id/textView2"
android:layout_weight="1" />
<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_alignTop="@+id/textView4"
android:layout_toRightOf="@+id/textView4"
android:layout_toEndOf="@+id/textView4"
android:layout_weight="1" />
</LinearLayout>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/seekBar"
android:paddingTop="10dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="false"
android:layout_alignParentLeft="false"
android:gravity="center_vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/forward"
android:id="@+id/button"
android:layout_weight="0.5" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pause"
android:id="@+id/button2"
android:layout_weight="3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/play"
android:id="@+id/button3"
android:layout_weight="3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/rewind"
android:id="@+id/button4"
android:layout_weight="0.5" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"></LinearLayout>
</RelativeLayout>
2.3. Код файла AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mnogoblog.ru.mediapleer3">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
2.4. Код файла strings.xml
<resources>
<string name="app_name">My Application</string>
<string name="play"><![CDATA[>]]></string>
<string name="rewind"><![CDATA[<<]]></string>
<string name="forward"><![CDATA[>>]]></string>
<string name="pause">||</string>
</resources>
На этом все, красивых вам Android приложений!


Здравствуйте.
Спасибо вам за урок.
Подскажите пожалуйста, как дальше добавлять песни, и есть ли какие то ограничения ?
И с помощью какого кода можно заменить перемотку на то, чтобы переключаться между песнями, подскажите пожалуйста..я абсолютный НОльвичок в этом…