Music Resource Management and playback on the Android platform, and android Resource Management

Source: Internet
Author: User

Music Resource Management and playback on the Android platform, and android Resource Management

The Android platform is based on the Linux and Open Mobile Alliance (OHA) systems. After innovative R & D by China Mobile, it has designed a novel and unique user operation interface, enhancing browser capabilities and WAP compatibility, optimized many well-known engines in the multimedia field such as OpenCORE and WebKit in the browser field, and added Advanced platform middleware including games, widgets, and Java ME. This article describes how to use the multimedia programming environment provided by the OPhone platform to manage and play music resources.

MediaScanner and music information Scanning
After the Android system is inserted into the SD card, the MediaScanner service automatically scans the file resources on the SD in the background and adds the music media information on the SD to the MediaStore database. The program can directly read the corresponding media information from MediaStore. By registering an Intent that listens to MediaScanner broadcasts, you can check whether the MediaScanner Service performs background scanning:

Intent. ACTION_MEDIA_SCANNER_STARTED indicates that MeidaScanner starts scanning;
Intent. ACTION_MEDIA_SCANNER_FINISHED indicates that the MediaScanner scan is completed;

After a program downloads a media file from the network to the terminal, the MediaScanner service does not automatically scan the downloaded file. The program needs to actively scan the newly added media file information to the MediaStore database. In Android, there are two ways to actively scan the information of music media files to the MediaStore database:

1. Start the MediaScanner service and scan media files:
The program starts the MediaScanner service to scan the specified file or directory by sending the following Intent:

Intent. ACTION_MEDIA_SCANNER_SCAN_FILE: scan a 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 scan mode, the current program process is not blocked because the scan is performed in the MediaScanner service. This scan method is applicable when scanning a large number of media files with low real-time requirements.

2. Scan media files through the API provided by MediaScanner.
This method of scanning media files is synchronous, and scanning will block the current program process. This scan method is applicable if you want to scan a small number of files and obtain scan results immediately.
Before scanning a media file, the program should correctly set the language environment of MediaScanner based on the current language environment of the terminal to avoid coding/decoding errors:
MediaScanner region = new MediaScanner (ctx );
Locale locale = ctx. getResources (). getConfiguration (). locale;
String language = locale. getLanguage ();
String country = locale. getCountry ();
Criteria. setLocale (language + \ "_ \" + country );
Media files can be stored in the memory of the mobile phone terminal or the SD card. The Android platform calls the mobile phone terminal memory as the internal storage space and the SD card as the external storage space. Media File Information in internal and external buckets is managed separately and each has an independent database. Therefore, when scanning a media file, you must specify whether the scanned media file is in an internal bucket or an external bucket. The volumes of the external and internal buckets are marked as "external" and "internal ".
Examples. scanSingleFile (filePath, volumeName, mimeType );
Metadata. scanDirectories (directories, volumeName );

MediaStore and music Information Query
MediaScanner stores all information obtained by scanning media files in the MediaStore database. MediaStore is based on the SQLite database system. Through the ContentProvider method, the program can add, query, modify, and delete MediaStore databases.
The database file of MediaStore is located in/data/com. android. providers/databases. Generally, two database files can be found.
Internal. db: the media database file corresponding to the internal storage space;
External-xxxxxxxx.db: corresponds to the external storage space of media data files, because the same mobile terminal may use multiple SD card, for each SD card, OPhone platform will generate the corresponding media database file.
The two database files are stored in different locations except for the managed files. This article will introduce external storage by default in the future.
Use the SQLite command to open the database file and you can see the basic structure of the Android multimedia database:
> Sqlite3 external-xxx.db
>. Tables
>. Schema
Interested readers can view it by themselves. This article will not list them one by one.

MediaStore is a multimedia database on the Android platform. It contains audio, video, images, and other multimedia file information. This article focuses on how to manage and obtain Audio Information, and how to obtain and manage audio information such as videos and images.
MediaStore provides media database information in the form of ContentProvider. The ContentProvider interface provided by the Android platform allows you to conveniently access 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: specify the name of the database to be queried and the name of the table. From MediaStore, we can find the parameters for the corresponding information. For details, see the SDK development documentation.
Prjs: Specifies the columns in the database table to be queried. The returned cursor contains the corresponding information. Null returns all information.
Selection: Specify query Conditions
SelectionArgs: Which of the following are in the selection parameter? This question mark can be replaced by the actual value. If selection does not exist? Then the String array can be null.
Order: Specify the order of query results

The MediaStore. Audio. Media class defines the song information in the Media database.
The MediaStore. Audio. Artists class defines information about singers 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.

You can use the OPhone SDK development documentation to find detailed information and use the ContentProvider query interface to obtain all media information.
MediaPlayer and MediaPlayer are the core classes in Android multimedia programming. It provides basic operations commonly used by a multimedia player, such as playing, pausing, stopping, and obtaining the playback length of a file. It uses the JNI encapsulation to obtain the multimedia playback capability provided by the system.
MeidaPlayer provides a well-designed multimedia interface. The process for playing an audio file is very simple:
1. Create a player: new MediaPlayer ()
2. Set the audio source: setDataSource (Audio_PATH)
3. prepare the audio source: prepare ()
4. play audio: start ()
5. stop playing: stop ()
6. release resources: release ();
Other commonly used MediaPlayer interfaces, such as pause (), getDuration (), and seekTo (). You can refer to the SDK documentation here.
The playing process of the audio is the state conversion process of the MediaPlayer object. A deep understanding of MediaPlayer's state machine is the basis for flexible control of Android multimedia programming. In the Android SDK development documentation, you can view the MediaPlayer status transition diagram. It is necessary for the program to monitor these changes and determine the status of the player. The Android platform provides multiple listeners to monitor the status changes of the MediaPlayer:
MediaPlayer. OnBufferingUpdateListener
MediaPlayer. OnCompletionListener
MediaPlayer. OnErrorListener
MediaPlayer. OnPreparedListener
MediaPlayer. OnSeekCompleteListener

The Android platform can play multimedia files in three ways: resource files, file systems, and networks. Regardless of the playback method, the basic process is similar.

Play from resource files
Multimedia files can be stored in the/res/raw directory of the resource folder, and then stored through MediaPlayer. create (Context ctx, int file) method to create a MediaPlayer object. After obtaining the MediaPlayer object, call the start () method to play the music.

Play from File System
To play music from a file system, you must use the new operator to create a MediaPlayer object. After obtaining the MediaPlayer object, you must call the setDataSource () and prepare () methods in sequence to set the data source, prepare the player, and then call the start () method to play the music.

Play from Network
The Android platform supports playing media music online and playing online audio resources through progress download. Progress download is supported by the underlying OpenCore multi-media library. application developers do not have to worry about the specific implementation details. They only need to set the Network Audio Resource address to complete online playback, this greatly improves the development efficiency. Since it takes a long time to download and play audio resources from the network, you need to use the prepareAsync () method when preparing the audio resources. This method is executed asynchronously, does not block the main process of the program. MediaPlayer notifies MediaPlayer of the preparation status through MediaPlayer. OnPreparedListener.
Under certain circumstances, the program needs to access online resources through the proxy server. For example, when accessing the network through the 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 a specified proxy to Access Network Audio resources: After the url of the network media, use "x-http-proxy" to specify the proxy server address. In addition, because the Android platform supports Multi PDP and multiple APN connections can be established at the same time, developers must specify which connection port needs to use the proxy server, use "x-net-interface" to specify the connection port (how to establish a CMWAP data connection and obtain the connection port name is not described in detail in this article, please refer to the relevant Android technical articles ), the following procedure describes how to play audio resources on the proxy server:
Private void playFromNetwork (){
String path = "http: // website/path/test.pdf ";
String CMWAP_HOST = "10.0.0.172 ";
String CMWAP_PORT = "80 ";

// Assume 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_INTERFACE;
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 ();
}
}

Related Article

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.