Initializing Audio Content for Playback

To play back audio content using the Media Player, you need to create a new Media Player object and set the data source of the audio in question.

To play back audio using the Media Player, you can use the static create method, passing in the application Context and one of the following (as shown in Listing 11-1):

> A resource identifier

> A URI to a local file using the file:// schema

> A URI to an online audio resource as a URL

> A URI to a local Content Provider row

Note that the Media Player object returned by the create methods have already had prepare called. It's important that you do not call it again.

Available for download on Context appContext = getApplicationContext(); Wrox.com

Available for download on Context appContext = getApplicationContext(); Wrox.com

MediaPlayer resourcePlayer = MediaPlayer.create(appContext,

R.raw.my_audio); MediaPlayer filePlayer = MediaPlayer.create(appContext,

Uri.parse("file:///sdcard/localfile.mp3")); MediaPlayer urlPlayer = MediaPlayer.create(appContext,

Uri.parse("http://site.com/audio/audio.mp3")); MediaPlayer contentPlayer = MediaPlayer.create(appContext, Settings.System.DEFAULT_RINGTONE_URI);

Alternatively, you can use the setDataSource method on an existing Media Player instance. This method accepts a file path, Content Provider URI, streaming media URL path, or File Descriptor.

When using the setDataSource method it is vital that you call prepare on the Media Player before you begin playback, as shown in Listing 11-2.

MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource("/sdcard/test.3gp") mediaPlayer.prepare();

Available for download on Wrox.com

MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource("/sdcard/test.3gp") mediaPlayer.prepare();

L J If you're passing a URL to an online media file, the file must be capable of ^^ progressive download using the RTSP or HTTP protocols.

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide


Post a comment