Music resource management and playback on the Android platform

Source: Internet
Author: User

Android platform based on the Linux and Open Mobile Alliance (OHA) system, through the Chinese Mobile Innovation Research and development, designed to have a new unique user interface, enhanced browser capabilities and WAP compatibility, optimize the multimedia field of Opencore, The browser field of WebKit and many other industry-renowned engines, including games, widgets, Java me and other advanced platform middleware. This paper mainly introduces how to use the multimedia programming environment provided by OPhone platform to manage and play music resources.

Mediascanner and music information scanning
Android system after the SD card is inserted, the Mediascanner service will automatically scan the SD file resources in the background and add music media information on the SD to the Mediastore database. The program can read the corresponding media information directly from the Mediastore. By registering to monitor Mediascanner broadcast intent, you can learn whether the Mediascanner service is scanning in the background:

Intent.action_media_scanner_started means meidascanner start scanning;
Intent.action_media_scanner_finished means the Mediascanner scan is finished;

When the program downloads media files from the network to the terminal, the Mediascanner service does not automatically scan the files that have just been downloaded and requires the program to proactively scan the newly added media files to the Mediastore database. There are two ways to actively scan the music media file information to the Mediastore database in the Android system:

1. Start the Mediascanner service and scan the media files:
The program scans the specified file or directory by sending the following intent to start the Mediascanner service:

Intent.action_media_scanner_scan_file: Scan the specified file

public void Scanfileasync (Context ctx, String filePath) {
Intent scanintent = new Intent (intent.action_media_scanner_scan_file);
Scanintent.setdata (Uri.fromfile (New File (FilePath)));
Ctx.sendbroadcast (scanintent);
}

"Android.intent.action.MEDIA_SCANNER_SCAN_DIR": Scan the specified directory

public static final String Action_media_scanner_scan_dir = "Android.intent.action.MEDIA_SCANNER_SCAN_DIR";
public void Scandirasync (Context ctx, String dir) {
Intent scanintent = new Intent (action_media_scanner_scan_dir);
Scanintent.setdata (Uri.fromfile new File (dir));
Ctx.sendbroadcast (scanintent);
}

In this scanning mode, the current program process is not blocked because the scan is done in the Mediascanner service. This scan is appropriate when scanning a large number of media files and not requiring high real-time performance.

2. Scan media files via the API interface provided by Mediascanner.
The way the media files are scanned is synchronized, and the scan will block the current program process. This scan is appropriate for cases where a small number of files are scanned and the scan results are required to be immediately available.
Before scanning media files, the program should correctly set Mediascanner locale settings according to the current language environment of the terminal to avoid codec errors:
Mediascanner scanner = new Mediascanner (CTX);
Locale locale = Ctx.getresources (). GetConfiguration (). Locale;
String language = Locale.getlanguage ();
String country = locale.getcountry ();
Scanner.setlocale (language + \ "_\" + country);
Media files can be stored in the memory of the phone terminal or stored in the SD card, the Android platform called the mobile phone terminal memory as internal storage space, called SD card as external storage space. The information about media files in internal and external storage is managed separately, and each has its own database management. Therefore, when scanning media files, it is necessary to specify whether the scanned media files are in internal or external storage space. The volume labeled "External" and "internal" corresponds to the external storage space and the internal storage space.
Scanner.scansinglefile (FilePath, VolumeName, MimeType);
Scanner.scandirectories (directories, volumename);

Mediastore and music information query
Mediascanner all the information obtained from the scanned media files is stored in the Mediastore database. Mediastore is based on the SQLite database system, through the ContentProvider way, the program can be Mediastore database additions and deletions to check and change operations.
Mediastore database files are located in/data/data/com.android.providers/databases and can typically be found in two database files
INTERNAL.DB: The media database file corresponding to the internal storage space;
EXTERNAL-XXXXXXXX.DB: The media data file corresponding to the external storage space, the OPhone platform will generate the corresponding media database file for each SD card because the same phone terminal may use multiple SD cards.
Two database files There is no other difference except where the managed files are stored in different locations. This article will be followed by default as an example of external storage.
Using the SQLite command to open the database file, you can see the basic structure of the Android multimedia database:
>sqlite3 external-xxx.db
>.tables
>.schema
Interested readers can see for themselves, this article is no longer listed.

The Mediastore class is a multimedia database of the Android platform that contains all of the multimedia file information such as audio, video, and images. This article will focus on how to manage and obtain audio information, such as video and pictures, and management of information similar to audio.
Mediastore provides media database information in the form of ContentProvider. The ContentProvider interface provided by the Android platform provides easy access to database information.
Public Cursor query (Contex ctx, Uri _uri, string[] Prjs, string selections, string[] Selectargs, string order) {
Contentresolver resolver = Ctx.getcontentresolver ();
if (resolver = = null) {
return null;
}
Return Resolver.query (_uri, Prjs, selections, Selectargs, order);
}

_uri: Indicates the name of the database to query, plus the name of the table, from Mediastore we can find the parameters of the corresponding information, please refer to the SDK development documentation.
PRJS: Specifies which columns in the database table are queried, and the corresponding information is included in the returned cursor. NULL returns all information.
Selection: Specifying query criteria
Selectionargs: Is there a parameter in selection? This symbol, you can replace the question mark with the actual value. What if selection this? , then this string array can be null
Order: Specify the order in which the query results are arranged

The MediaStore.Audio.Media class defines the song information in the media database
The MediaStore.Audio.Artists class defines the singer information in the media database
The MediaStore.Audio.Albums class defines the album information in the Media database
The MediaStore.Audio.Playlists class defines the playlist information in the media database

Readers can find detailed information through the OPhone SDK Development documentation, combined with ContentProvider's query interface, to obtain all media information.
MediaPlayer and music playback MediaPlayer are the core classes in Android multimedia programming. It provides a multimedia player commonly used for basic operations such as play, pause, stop, get file playback length and so on. It is down through the JNI encapsulation to get the multimedia playback capability provided by the system.
Meidaplayer provides a well-designed multimedia interface, and the steps to play an audio file are simple:
1. Create player: New MediaPlayer ()
2. Set the audio Source: Setdatasource (Audio_path)
3. Prepare the audio Source: Prepare ()
4. Play Audio: Start ()
5. Stop playback: Stop ()
6. Releasing resources: Release ();
Other MediaPlayer commonly used interfaces such as pause (), getduration (), Seekto (), etc., you can check the SDK documentation yourself, not described here.
The audio playback process is also the MediaPlayer object's state transition process. An in-depth understanding of MediaPlayer's state machine is the basis for flexible Android multimedia programming. In the Android SDK Development documentation, readers can view the MediaPlayer state transition diagram. It is necessary for the program to listen for these changes and to determine the status of the player, and the Android platform provides a variety of listeners to monitor the MediaPlayer status changes:
Mediaplayer.onbufferingupdatelistener
Mediaplayer.oncompletionlistener
Mediaplayer.onerrorlistener
Mediaplayer.onpreparedlistener
Mediaplayer.onseekcompletelistener

The Android platform can play multimedia files in three ways, from resource files, file systems, and networks. The basic process is similar, regardless of which playback method is used.

Play from a resource file
The multimedia file can be placed in the Resource folder/res/raw directory, and then the MediaPlayer object is created through the mediaplayer.create (Context ctx, int file) method. You can play music by calling the start () method directly after you get the MediaPlayer object.

Play from File system
To play music from the file system, you need to create a MediaPlayer object using the new operator. After you get the MediaPlayer object, you need to call the Setdatasource () and prepare () methods in turn to set up the data source, let the player complete the preparation, and then call the start () method to play the music.

Play from the network
The Android platform supports playing media music online, playing online audio resources by progress download. Progress download support from the bottom of the Opencore Multimedia library to provide support, application developers do not care about the specific implementation details, only need to set the address of the network audio resources, you can complete the work of online playback, greatly improving the development efficiency. Because it takes a long time to download audio resources from the network, you need to use the Prepareasync () method when preparing the audio resource, which is executed asynchronously and does not block the program's main process. MediaPlayer notifies MediaPlayer of readiness by Mediaplayer.onpreparedlistener.
In certain cases, the program needs to access the online resources through a proxy server, for example, when accessing the network through APN Cmwap, you need to set the proxy address (10.0.0.172:80) of the Cmwap. The Android platform provides a very convenient solution that allows developers to easily notify Opencore to use the specified proxy to access network Audio resources: After the URL of the network media, specify the proxy server address via "X-http-proxy". Also, since the Android platform supports multi PDP, multiple APN connections can be established at the same time, so the developer must indicate which connection port needs to use a proxy server and specify the connection port via "X-net-interface" (how to establish a Cmwap data connection, To get the connection port name, which is not described in detail in this article, please see the relevant Android technical article, the following procedure briefly describes the steps to play an audio resource through a proxy server:
private void Playfromnetwork () {
String Path = "Http://website/path/test.mp3";
String cmwap_host = "10.0.0.172";
String cmwap_port = "80";

Suppose the port name of the Cmwap connection
String socket_interface = "Cminnet0";

String urlwithproxy = path + "? x-http-proxy=" + Cmwap_host + ":" + Cmwap_port + "&" + "x-net-interface=" + socket_inte Rface;
try {
MediaPlayer player = new MediaPlayer ();
Player.setdatasource (path);
Player.setonpreparedlistener (New Mediaplayer.onpreparedlistener () {
public void onprepared (MediaPlayer player) {
Player.start ();
}
});
Player.prepareasync ();
} catch (Exception e) {
E.printstacktrace ();
}
}

Music resource management and playback on the Android platform

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.