How to Read From a Mediaplayer File in Raw for Android
Android - MediaPlayer
Android provides many ways to control playback of audio/video files and streams. One of this way is through a grade called MediaPlayer.
Android is providing MediaPlayer class to admission built-in mediaplayer services similar playing audio,video east.t.c. In order to use MediaPlayer, we accept to telephone call a static Method create() of this class. This method returns an instance of MediaPlayer class. Its syntax is as follows −
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
The second parameter is the name of the song that you want to play. You take to brand a new folder under your project with name raw and place the music file into it.
One time you have created the Mediaplayer object you can call some methods to first or finish the music. These methods are listed below.
mediaPlayer.get-go(); mediaPlayer.pause();
On call to kickoff() method, the music will showtime playing from the beginning. If this method is called again afterward the intermission() method, the music would get-go playing from where it is left and non from the beginning.
In order to start music from the beginning, yous have to call reset() method. Its syntax is given below.
mediaPlayer.reset();
Apart from the start and pause method, there are other methods provided by this course for better dealing with sound/video files. These methods are listed below −
Sr.No | Method & description |
---|---|
ane | isPlaying() This method only returns true/imitation indicating the vocal is playing or not |
2 | seekTo(position) This method takes an integer, and motion song to that item position millisecond |
3 | getCurrentPosition() This method returns the current position of song in milliseconds |
four | getDuration() This method returns the total fourth dimension elapsing of song in milliseconds |
5 | reset() This method resets the media player |
6 | release() This method releases any resources fastened with MediaPlayer object |
seven | setVolume(float leftVolume, float rightVolume) This method sets the up downwards volume for this role player |
8 | setDataSource(FileDescriptor fd) This method sets the data source of audio/video file |
9 | selectTrack(int alphabetize) This method takes an integer, and select the runway from the list on that particular index |
x | getTrackInfo() This method returns an array of rails information |
Case
Here is an example demonstrating the utilise of MediaPlayer form. It creates a basic media player that allows you to forward, backward, play and break a song.
To experiment with this example, yous need to run this on an actual device to hear the audio sound.
Steps | Description |
---|---|
i | You will utilise Android studio IDE to create an Android awarding under a bundle com.case.sairamkrishna.myapplication. |
2 | Modify src/MainActivity.coffee file to add together MediaPlayer code. |
3 | Change the res/layout/activity_main to add respective XML components |
4 | Create a new folder under MediaPlayer with name as raw and identify an mp3 music file in information technology with name as vocal.mp3 |
five | Run the application and choose a running android device and install the application on it and verify the results |
Following is the content of the modified main action file src/MainActivity.java.
bundle com.example.sairamkrishna.myapplication; import android.app.Activity; import android.media.MediaPlayer; import android.bone.Parcel; import android.bone.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 coffee.util.concurrent.TimeUnit; public class MainActivity extends Activity { private Push 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; individual TextView tx1,tx2,tx3; public static int oneTimeOnly = 0; @Override protected void onCreate(Parcel 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.vocal); seekbar = (SeekBar)findViewById(R.id.seekBar); seekbar.setClickable(false); b2.setEnabled(simulated); b3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "Playing audio",Toast.LENGTH_SHORT).prove(); 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(faux); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "Pausing sound",Toast.LENGTH_SHORT).show(); mediaPlayer.intermission(); 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 accept Jumped forrad v seconds",Toast.LENGTH_SHORT).evidence(); }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 accept Jumped backward 5 seconds",Toast.LENGTH_SHORT).testify(); }else{ Toast.makeText(getApplicationContext(),"Cannot bound astern five seconds",Toast.LENGTH_SHORT).evidence(); } } }); } individual 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); } }; }
Following is the modified content of the xml res/layout/activity_main.xml.
In the beneath code abcindicates the logo of 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"/> <Push 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" /> <Push 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" /> <Push 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/push button" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall" android:text="Pocket-size 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>
Following is the content of the res/values/string.xml.
<resources> <string name="app_name">My Application</string> <string name="dorsum"><![CDATA[<]]></string> <string name="rewind"><![CDATA[<<]]></string> <string name="forward"><![CDATA[>>]]></cord> <string name="pause">||</string> </resources>
Following is the content of AndroidManifest.xml file.
<?xml version="ane.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" bundle="com.example.sairamkrishna.myapplication" > <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <action 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> </awarding> </manifest>
Let'south try to run your awarding. I assume you take connected your actual Android Mobile device with your computer. To run the app from Eclipse, open i of your project's activity files and click Run icon from the toolbar. Before starting your awarding, Android studio will brandish following screens
By default you would see the pause button disabled. Now press play button and information technology would become disable and break push go enable. Information technology is shown in the moving picture beneath −
Up till at present, the music has been playing. Now press the suspension button and see the pause notification. This is shown below −
Now when you printing the play push again, the song will not play from the offset just from where information technology was paused. Now press the fast frontward or astern button to jump the song forrad or astern 5 seconds. A fourth dimension came when the vocal cannot be jump frontward. At this point , the notification would announced which would be something similar this −
Your music would remain playing in the background while you are doing other tasks in your mobile. In order to stop it , you lot take to exit this application from background activities.
Above image shows when y'all pick rewind push.
Useful Video Courses
Video
Video
Video
Video
Video
Video
Source: https://www.tutorialspoint.com/android/android_mediaplayer.htm
Postar um comentário for "How to Read From a Mediaplayer File in Raw for Android"