See
Audio
and Video,
the
MediaPlayer
state diagram,
and the list of
approved
formats.
mediaplayer_1.xml
creates four buttons.strings.xml
has the captions for the four buttons:
MediaPlayerDemo.java
displays the four buttons.
When a button is pressed, it uses an
Intent
object to go hunting for an
Activity
of class
MediaPlayerDemo_Audio
.MediaPlayerDemo_Audio.java
creates a
MediaPlayer
object and
start
s
it.
Go
here
and download the sound file
China-sound--Lo-Fi-Preview-.mp3
.
Right-click on the
res
folder in the Eclipse Package Explorer,
select New → Folder,
and create a subfolder named
raw
.
Rename the file
china.mp3
(no uppercase or dashes)
and drag it into
raw
.
Select how files should be imported into the project:
• Copy files
OK
In
main.xml
,
change the
LinearLayout
to a
RelativeLayout
.
Then give the
ToggleButton
the following attribute.
android:layout_centerInParent="true"See RelativeLayout in Common Layout Objects.
res/raw
directory.
In the
onClick
method of the
OnClickListener
,
change
mediaPlayer = MediaPlayer.create(AudioActivity.this, R.raw.china); //calls prepare if (mediaPlayer == null) { Toast.makeText(AudioActivity.this, "couldn't create MediaPayer", Toast.LENGTH_LONG).show(); return; }to
mediaPlayer = new MediaPlayer(); if (mediaPlayer == null) { Toast.makeText(AudioActivity.this, "mediaPlayer is null", Toast.LENGTH_LONG).show(); return; } try { mediaPlayer.setDataSource( "http://oit2.scps.nyu.edu/~meretzkm/INFO1-CE9236/src/button/chinese.mp3" ); } catch (Exception e) { Toast.makeText(AudioActivity.this, e.toString(), Toast.LENGTH_LONG).show(); return; } try { mediaPlayer.prepare(); } catch (Exception e) { Toast.makeText(AudioActivity.this, e.toString(), Toast.LENGTH_LONG).show(); return; }Surprisingly, it is not necessary to add the following element to the
manifest
element in
AndroidManifest.xml
.
<uses-permission android:name="android.permission.INTERNET"/>If downloading the sound file causes an annoying delay after the button is pressed, download the sound file when the
Activity
is created.
setDataSource
worked with a
.mp3
file but threw an exception with a
.mid
file.
Why?
The
.mid
file worked when I put it in the
res/raw
directory.
/data
directory of the file system of the Android Emulator
with the following commands in the Mac Terminal
or the Windows command prompt
cmd.exe
.
cd Desktop adb shell ls -l /data
adb push myfile.mp3 /data 100 KB/s (219596 bytes in 2.128s)
adb shell ls -l /data -rw-rw-rw- root root 219596 2011-06-28 15:50 myfile.mp3Change the call to
setDataSource
to the following.
It has a triple slash.
mediaPlayer.setDataSource("file:///data/myfile.mp3");
ApiDemos/Media/AudioFx
.