upload android base code part1

This commit is contained in:
August 2018-08-08 15:50:00 +08:00
parent e02f198e2d
commit 0a1de6c4b3
48159 changed files with 9071466 additions and 0 deletions

View file

@ -0,0 +1,144 @@
// slesTest_playStates
cc_test {
name: "slesTest_playStates",
gtest: false,
srcs: ["slesTest_playStates.cpp"],
shared_libs: ["libOpenSLES"],
cflags: [
"-Werror",
"-Wall",
"-UNDEBUG",
],
}
// slesTest_playStreamType
cc_test {
name: "slesTest_playStreamType",
gtest: false,
srcs: ["slesTestPlayStreamType.cpp"],
shared_libs: ["libOpenSLES"],
cflags: [
"-Werror",
"-Wall",
"-UNDEBUG",
],
}
// slesTest_playUri
cc_test {
name: "slesTest_playUri",
gtest: false,
srcs: ["slesTestPlayUri.cpp"],
shared_libs: ["libOpenSLES"],
cflags: [
"-Werror",
"-Wall",
"-UNDEBUG",
],
}
// slesTest_loopUri
cc_test {
name: "slesTest_loopUri",
gtest: false,
srcs: ["slesTestLoopUri.cpp"],
shared_libs: ["libOpenSLES"],
cflags: [
"-Werror",
"-Wall",
"-UNDEBUG",
],
}
// slesTest_playUri2
cc_test {
name: "slesTest_playUri2",
gtest: false,
srcs: ["slesTestPlayUri2.cpp"],
shared_libs: ["libOpenSLES"],
cflags: [
"-Werror",
"-Wall",
"-UNDEBUG",
],
}
// slesTest_slowDownUri
cc_test {
name: "slesTest_slowDownUri",
gtest: false,
srcs: ["slesTestSlowDownUri.cpp"],
shared_libs: ["libOpenSLES"],
cflags: [
"-Werror",
"-Wall",
"-UNDEBUG",
],
}
// slesTest_manyPlayers
cc_test {
name: "slesTest_manyPlayers",
gtest: false,
srcs: ["slesTestManyPlayers.cpp"],
shared_libs: ["libOpenSLES"],
cflags: [
"-Werror",
"-Wall",
"-UNDEBUG",
],
}
// slesTest_getPositionUri
cc_test {
name: "slesTest_getPositionUri",
gtest: false,
srcs: ["slesTestGetPositionUri.cpp"],
shared_libs: ["libOpenSLES"],
cflags: [
"-Werror",
"-Wall",
"-UNDEBUG",
],
}

View file

@ -0,0 +1,343 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <utils/threads.h>
#include <SLES/OpenSLES.h>
/* tolerance in ms for this test in time difference between reported position and time since
* playback was requested to start. This is reasonable for a local file.
*/
#define TIME_TOLERANCE_MS 600
/* explicitly requesting SL_IID_VOLUME and SL_IID_PREFETCHSTATUS
* on the AudioPlayer object */
#define NUM_EXPLICIT_INTERFACES_FOR_PLAYER 2
/* used to detect errors likely to have occured when the OpenSL ES framework fails to open
* a resource, for instance because a file URI is invalid, or an HTTP server doesn't respond. */
#define PREFETCHEVENT_ERROR_CANDIDATE \
(SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE)
/* to signal to the test app the end of the stream to decode has been reached */
bool eos = false;
android::Mutex eosLock;
android::Condition eosCondition;
//-----------------------------------------------------------------
//* Exits the application if an error is encountered */
#define CheckErr(x) ExitOnErrorFunc(x,__LINE__)
void ExitOnErrorFunc( SLresult result , int line)
{
if (SL_RESULT_SUCCESS != result) {
fprintf(stderr, "%u error code encountered at line %d, exiting\n", result, line);
exit(EXIT_FAILURE);
}
}
bool prefetchError = false;
//-----------------------------------------------------------------
void SignalEos() {
android::Mutex::Autolock autoLock(eosLock);
eos = true;
eosCondition.signal();
}
//-----------------------------------------------------------------
/* PrefetchStatusItf callback for an audio player */
void PrefetchEventCallback( SLPrefetchStatusItf caller, void *pContext __unused, SLuint32 event)
{
SLpermille level = 0;
SLresult res = (*caller)->GetFillLevel(caller, &level); CheckErr(res);
SLuint32 status;
//fprintf(stdout, "PrefetchEventCallback: received event %u\n", event);
res = (*caller)->GetPrefetchStatus(caller, &status); CheckErr(res);
if ((PREFETCHEVENT_ERROR_CANDIDATE == (event & PREFETCHEVENT_ERROR_CANDIDATE))
&& (level == 0) && (status == SL_PREFETCHSTATUS_UNDERFLOW)) {
fprintf(stdout, "PrefetchEventCallback: Error while prefetching data, exiting\n");
prefetchError = true;
return;
}
if (event & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
fprintf(stdout, "PrefetchEventCallback: Buffer fill level is = %d\n", level);
}
if (event & SL_PREFETCHEVENT_STATUSCHANGE) {
fprintf(stdout, "PrefetchEventCallback: Prefetch Status is = %u\n", status);
}
}
//-----------------------------------------------------------------
/* PlayItf callback for playback events */
void PlayEventCallback(
SLPlayItf caller,
void *pContext __unused,
SLuint32 event)
{
SLmillisecond posMsec = SL_TIME_UNKNOWN;
SLresult res;
if (SL_PLAYEVENT_HEADATEND & event) {
fprintf(stdout, "SL_PLAYEVENT_HEADATEND reached\n");
#if 0
res = (*caller)->GetPosition(caller, &posMsec); CheckErr(res);
fprintf(stdout, "after getPosition in SL_PLAYEVENT_HEADATEND handler\n");
if (posMsec == SL_TIME_UNKNOWN) {
fprintf(stderr, "Error: position is SL_TIME_UNKNOWN at SL_PLAYEVENT_HEADATEND\n");
} else {
fprintf(stdout, "position is %d at SL_PLAYEVENT_HEADATEND\n", posMsec);
}
// FIXME compare position against duration
#endif
SignalEos();
}
if (SL_PLAYEVENT_HEADATNEWPOS & event) {
res = (*caller)->GetPosition(caller, &posMsec); CheckErr(res);
fprintf(stdout, "SL_PLAYEVENT_HEADATNEWPOS current position=%ums\n", posMsec);
}
if (SL_PLAYEVENT_HEADATMARKER & event) {
res = (*caller)->GetPosition(caller, &posMsec); CheckErr(res);
fprintf(stdout, "SL_PLAYEVENT_HEADATMARKER current position=%ums\n", posMsec);
}
}
//-----------------------------------------------------------------
/* Play some audio from a URI and regularly query the position */
void TestGetPositionUri( SLObjectItf sl, const char* path)
{
SLEngineItf EngineItf;
SLresult res;
SLDataSource audioSource;
SLDataLocator_URI uri;
SLDataFormat_MIME mime;
SLDataSink audioSink;
SLDataLocator_OutputMix locator_outputmix;
SLObjectItf player;
SLPlayItf playItf;
SLVolumeItf volItf;
SLPrefetchStatusItf prefetchItf;
SLObjectItf OutputMix;
/* variables for the duration and position tests */
SLuint16 counter = 0;
SLmillisecond posInMsec = SL_TIME_UNKNOWN;
SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
SLboolean required[NUM_EXPLICIT_INTERFACES_FOR_PLAYER];
SLInterfaceID iidArray[NUM_EXPLICIT_INTERFACES_FOR_PLAYER];
/* Get the SL Engine Interface which is implicit */
res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);
CheckErr(res);
/* Initialize arrays required[] and iidArray[] */
for (int i=0 ; i < NUM_EXPLICIT_INTERFACES_FOR_PLAYER ; i++) {
required[i] = SL_BOOLEAN_FALSE;
iidArray[i] = SL_IID_NULL;
}
// Set arrays required[] and iidArray[] for VOLUME and PREFETCHSTATUS interface
required[0] = SL_BOOLEAN_TRUE;
iidArray[0] = SL_IID_VOLUME;
required[1] = SL_BOOLEAN_TRUE;
iidArray[1] = SL_IID_PREFETCHSTATUS;
// Create Output Mix object to be used by player
res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0,
iidArray, required); CheckErr(res);
// Realizing the Output Mix object in synchronous mode.
res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE);
CheckErr(res);
/* Setup the data source structure for the URI */
uri.locatorType = SL_DATALOCATOR_URI;
uri.URI = (SLchar*) path;
mime.formatType = SL_DATAFORMAT_MIME;
mime.mimeType = (SLchar*)NULL;
mime.containerType = SL_CONTAINERTYPE_UNSPECIFIED;
audioSource.pFormat = (void *)&mime;
audioSource.pLocator = (void *)&uri;
/* Setup the data sink structure */
locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX;
locator_outputmix.outputMix = OutputMix;
audioSink.pLocator = (void *)&locator_outputmix;
audioSink.pFormat = NULL;
/* Create the audio player */
res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink,
NUM_EXPLICIT_INTERFACES_FOR_PLAYER, iidArray, required); CheckErr(res);
/* Realizing the player in synchronous mode. */
res = (*player)->Realize(player, SL_BOOLEAN_FALSE); CheckErr(res);
fprintf(stdout, "URI example: after Realize\n");
/* Get interfaces */
res = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf);
CheckErr(res);
res = (*player)->GetInterface(player, SL_IID_VOLUME, (void*)&volItf);
CheckErr(res);
res = (*player)->GetInterface(player, SL_IID_PREFETCHSTATUS, (void*)&prefetchItf);
CheckErr(res);
res = (*prefetchItf)->RegisterCallback(prefetchItf, PrefetchEventCallback, &prefetchItf);
CheckErr(res);
res = (*prefetchItf)->SetCallbackEventsMask(prefetchItf,
SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE);
CheckErr(res);
/* Configure fill level updates every 5 percent */
res = (*prefetchItf)->SetFillUpdatePeriod(prefetchItf, 50); CheckErr(res);
/* Set up the player callback to get events during the decoding */
res = (*playItf)->SetMarkerPosition(playItf, 2000);
CheckErr(res);
res = (*playItf)->SetPositionUpdatePeriod(playItf, 500);
CheckErr(res);
res = (*playItf)->SetCallbackEventsMask(playItf,
SL_PLAYEVENT_HEADATMARKER | SL_PLAYEVENT_HEADATNEWPOS | SL_PLAYEVENT_HEADATEND);
CheckErr(res);
res = (*playItf)->RegisterCallback(playItf, PlayEventCallback, NULL);
CheckErr(res);
/* Set the player volume */
res = (*volItf)->SetVolumeLevel( volItf, -300);
CheckErr(res);
/* Play the URI */
/* first cause the player to prefetch the data */
fprintf(stdout, "Setting the player to PAUSED to cause it to prefetch the data\n");
res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED ); CheckErr(res);
usleep(100 * 1000);
/* wait until there's data to play */
SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW;
SLuint32 timeOutIndex = 100; // 10s
while ((prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) && (timeOutIndex > 0) &&
!prefetchError) {
usleep(100 * 1000);
(*prefetchItf)->GetPrefetchStatus(prefetchItf, &prefetchStatus);
timeOutIndex--;
}
if (timeOutIndex == 0 || prefetchError) {
fprintf(stderr, "We're done waiting, failed to prefetch data in time, exiting\n");
goto destroyRes;
}
/* Display duration */
res = (*playItf)->GetDuration(playItf, &durationInMsec); CheckErr(res);
if (durationInMsec == SL_TIME_UNKNOWN) {
fprintf(stderr, "Error: Content duration is unknown after prefetch completed, exiting\n");
goto destroyRes;
} else {
fprintf(stdout, "Content duration is %u ms (after prefetch completed)\n", durationInMsec);
}
fprintf(stdout, "Setting the player to PLAYING\n");
res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING ); CheckErr(res);
/* Test GetPosition every second */
while ((counter*1000) < durationInMsec) {
counter++;
usleep(1 * 1000 * 1000); //1s
res = (*playItf)->GetPosition(playItf, &posInMsec); CheckErr(res);
if (posInMsec == SL_TIME_UNKNOWN) {
fprintf(stderr, "Error: position is SL_TIME_UNKNOWN %ds after start, exiting\n",
counter);
goto destroyRes;
} else {
fprintf(stderr, "position is %dms %ds after start\n", posInMsec, counter);
}
// this test would probably deserve to be improved by relying on drift relative to
// a clock, as the operations between two consecutive sleep() are taking time as well
// and can add up
if (((SLint32)posInMsec > (counter*1000 + TIME_TOLERANCE_MS)) ||
((SLint32)posInMsec < (counter*1000 - TIME_TOLERANCE_MS))) {
fprintf(stderr, "Error: position drifted too much, exiting\n");
goto destroyRes;
}
}
/* Play until the end of file is reached */
{
android::Mutex::Autolock autoLock(eosLock);
while (!eos) {
eosCondition.wait(eosLock);
}
}
fprintf(stdout, "EOS signaled, stopping playback\n");
res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED); CheckErr(res);
destroyRes:
/* Destroy the player */
fprintf(stdout, "Destroying the player\n");
(*player)->Destroy(player);
/* Destroy Output Mix object */
(*OutputMix)->Destroy(OutputMix);
}
//-----------------------------------------------------------------
int main(int argc, char* const argv[])
{
SLresult res;
SLObjectItf sl;
fprintf(stdout, "OpenSL ES test %s: exercises SLPlayItf", argv[0]);
fprintf(stdout, "and AudioPlayer with SLDataLocator_URI source / OutputMix sink\n");
fprintf(stdout, "Plays a sound and requests position at various times\n\n");
if (argc == 1) {
fprintf(stdout, "Usage: %s path \n\t%s url\n", argv[0], argv[0]);
fprintf(stdout, "Example: \"%s /sdcard/my.mp3\" or \"%s file:///sdcard/my.mp3\"\n",
argv[0], argv[0]);
exit(EXIT_FAILURE);
}
SLEngineOption EngineOption[] = {
{(SLuint32) SL_ENGINEOPTION_THREADSAFE,
(SLuint32) SL_BOOLEAN_TRUE}};
res = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
CheckErr(res);
/* Realizing the SL Engine in synchronous mode. */
res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
CheckErr(res);
TestGetPositionUri(sl, argv[1]);
/* Shutdown OpenSL ES */
(*sl)->Destroy(sl);
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,318 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <assert.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <SLES/OpenSLES.h>
#define MAX_NUMBER_INTERFACES 2
#define REPETITIONS 4
// These are extensions to OpenSL ES 1.0.1 values
#define SL_PREFETCHSTATUS_UNKNOWN 0
#define SL_PREFETCHSTATUS_ERROR ((SLuint32) -1)
// Mutex and condition shared with main program to protect prefetch_status
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
SLuint32 prefetch_status = SL_PREFETCHSTATUS_UNKNOWN;
/* used to detect errors likely to have occured when the OpenSL ES framework fails to open
* a resource, for instance because a file URI is invalid, or an HTTP server doesn't respond.
*/
#define PREFETCHEVENT_ERROR_CANDIDATE \
(SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE)
//-----------------------------------------------------------------
//* Exits the application if an error is encountered */
#define CheckErr(x) ExitOnErrorFunc(x,__LINE__)
void ExitOnErrorFunc( SLresult result , int line)
{
if (SL_RESULT_SUCCESS != result) {
fprintf(stderr, "%u error code encountered at line %d, exiting\n", result, line);
exit(EXIT_FAILURE);
}
}
//-----------------------------------------------------------------
/* PrefetchStatusItf callback for an audio player */
void PrefetchEventCallback( SLPrefetchStatusItf caller, void *pContext, SLuint32 event)
{
SLresult result;
// pContext is unused here, so we pass NULL
assert(pContext == NULL);
SLpermille level = 0;
result = (*caller)->GetFillLevel(caller, &level);
CheckErr(result);
SLuint32 status;
result = (*caller)->GetPrefetchStatus(caller, &status);
CheckErr(result);
if (event & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
fprintf(stdout, "\t\tPrefetchEventCallback: Buffer fill level is = %d\n", level);
}
if (event & SL_PREFETCHEVENT_STATUSCHANGE) {
fprintf(stdout, "\t\tPrefetchEventCallback: Prefetch Status is = %u\n", status);
}
SLuint32 new_prefetch_status;
if ((event & PREFETCHEVENT_ERROR_CANDIDATE) == PREFETCHEVENT_ERROR_CANDIDATE
&& (level == 0) && (status == SL_PREFETCHSTATUS_UNDERFLOW)) {
fprintf(stdout, "\t\tPrefetchEventCallback: Error while prefetching data, exiting\n");
new_prefetch_status = SL_PREFETCHSTATUS_ERROR;
} else if (event == SL_PREFETCHEVENT_STATUSCHANGE &&
status == SL_PREFETCHSTATUS_SUFFICIENTDATA) {
new_prefetch_status = status;
} else {
return;
}
int ok;
ok = pthread_mutex_lock(&mutex);
assert(ok == 0);
prefetch_status = new_prefetch_status;
ok = pthread_cond_signal(&cond);
assert(ok == 0);
ok = pthread_mutex_unlock(&mutex);
assert(ok == 0);
}
//-----------------------------------------------------------------
/* PlayItf callback for playback events */
void PlayEventCallback(
SLPlayItf caller __unused,
void *pContext,
SLuint32 event)
{
// pContext is unused here, so we pass NULL
assert(NULL == pContext);
if (SL_PLAYEVENT_HEADATEND == event) {
printf("SL_PLAYEVENT_HEADATEND reached\n");
} else {
fprintf(stderr, "Unexpected play event 0x%x", event);
}
}
//-----------------------------------------------------------------
/* Play some music from a URI */
void TestLoopUri( SLObjectItf sl, const char* path)
{
SLEngineItf EngineItf;
SLresult res;
SLDataSource audioSource;
SLDataLocator_URI uri;
SLDataFormat_MIME mime;
SLDataSink audioSink;
SLDataLocator_OutputMix locator_outputmix;
SLObjectItf player;
SLPlayItf playItf;
SLSeekItf seekItf;
SLPrefetchStatusItf prefetchItf;
SLObjectItf OutputMix;
SLboolean required[MAX_NUMBER_INTERFACES];
SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
/* Get the SL Engine Interface which is implicit */
res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);
CheckErr(res);
/* Initialize arrays required[] and iidArray[] */
for (int i=0 ; i < MAX_NUMBER_INTERFACES ; i++) {
required[i] = SL_BOOLEAN_FALSE;
iidArray[i] = SL_IID_NULL;
}
required[0] = SL_BOOLEAN_TRUE;
iidArray[0] = SL_IID_VOLUME;
// Create Output Mix object to be used by player
res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0,
iidArray, required); CheckErr(res);
// Realizing the Output Mix object in synchronous mode.
res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE);
CheckErr(res);
/* Setup the data source structure for the URI */
uri.locatorType = SL_DATALOCATOR_URI;
uri.URI = (SLchar*) path;
mime.formatType = SL_DATAFORMAT_MIME;
mime.mimeType = (SLchar*)NULL;
mime.containerType = SL_CONTAINERTYPE_UNSPECIFIED;
audioSource.pFormat = (void *)&mime;
audioSource.pLocator = (void *)&uri;
/* Setup the data sink structure */
locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX;
locator_outputmix.outputMix = OutputMix;
audioSink.pLocator = (void *)&locator_outputmix;
audioSink.pFormat = NULL;
/* Create the audio player */
required[0] = SL_BOOLEAN_TRUE;
iidArray[0] = SL_IID_SEEK;
required[1] = SL_BOOLEAN_TRUE;
iidArray[1] = SL_IID_PREFETCHSTATUS;
res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink,
MAX_NUMBER_INTERFACES, iidArray, required); CheckErr(res);
/* Realizing the player in synchronous mode. */
res = (*player)->Realize(player, SL_BOOLEAN_FALSE); CheckErr(res);
fprintf(stdout, "URI example: after Realize\n");
/* Get interfaces */
res = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf);
CheckErr(res);
res = (*player)->GetInterface(player, SL_IID_SEEK, (void*)&seekItf);
CheckErr(res);
res = (*player)->GetInterface(player, SL_IID_PREFETCHSTATUS, (void*)&prefetchItf);
CheckErr(res);
res = (*prefetchItf)->RegisterCallback(prefetchItf, PrefetchEventCallback, NULL);
CheckErr(res);
res = (*prefetchItf)->SetCallbackEventsMask(prefetchItf,
SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE);
CheckErr(res);
/* Configure fill level updates every 5 percent */
(*prefetchItf)->SetFillUpdatePeriod(prefetchItf, 50);
/* Set up the player callback to get head-at-end events */
res = (*playItf)->SetCallbackEventsMask(playItf, SL_PLAYEVENT_HEADATEND);
CheckErr(res);
res = (*playItf)->RegisterCallback(playItf, PlayEventCallback, NULL);
CheckErr(res);
/* Display duration */
SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
res = (*playItf)->GetDuration(playItf, &durationInMsec);
CheckErr(res);
if (durationInMsec == SL_TIME_UNKNOWN) {
fprintf(stdout, "Content duration is unknown (before starting to prefetch)\n");
} else {
fprintf(stdout, "Content duration is %u ms (before starting to prefetch)\n",
durationInMsec);
}
/* Loop on the whole of the content */
res = (*seekItf)->SetLoop(seekItf, SL_BOOLEAN_TRUE, 0, SL_TIME_UNKNOWN);
CheckErr(res);
/* Play the URI */
/* first cause the player to prefetch the data */
res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED );
CheckErr(res);
// wait for prefetch status callback to indicate either sufficient data or error
pthread_mutex_lock(&mutex);
while (prefetch_status == SL_PREFETCHSTATUS_UNKNOWN) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
if (prefetch_status == SL_PREFETCHSTATUS_ERROR) {
fprintf(stderr, "Error during prefetch, exiting\n");
goto destroyRes;
}
/* Display duration again, */
res = (*playItf)->GetDuration(playItf, &durationInMsec);
CheckErr(res);
if (durationInMsec == SL_TIME_UNKNOWN) {
fprintf(stdout, "Content duration is unknown (after prefetch completed)\n");
} else {
fprintf(stdout, "Content duration is %u ms (after prefetch completed)\n", durationInMsec);
}
/* Start playing */
fprintf(stdout, "starting to play\n");
res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING );
CheckErr(res);
/* Wait as long as the duration of the content, times the repetitions,
* before stopping the loop */
usleep( (REPETITIONS-1) * durationInMsec * 1100);
res = (*seekItf)->SetLoop(seekItf, SL_BOOLEAN_FALSE, 0, SL_TIME_UNKNOWN);
CheckErr(res);
fprintf(stdout, "As of now, stopped looping (sound shouldn't repeat from now on)\n");
/* wait some more to make sure it doesn't repeat */
usleep(durationInMsec * 1000);
/* Stop playback */
fprintf(stdout, "stopping playback\n");
res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
CheckErr(res);
destroyRes:
/* Destroy the player */
(*player)->Destroy(player);
/* Destroy Output Mix object */
(*OutputMix)->Destroy(OutputMix);
}
//-----------------------------------------------------------------
int main(int argc, char* const argv[])
{
SLresult res;
SLObjectItf sl;
fprintf(stdout, "OpenSL ES test %s: exercises SLPlayItf, SLSeekItf ", argv[0]);
fprintf(stdout, "and AudioPlayer with SLDataLocator_URI source / OutputMix sink\n");
fprintf(stdout, "Plays a sound and loops it %d times.\n\n", REPETITIONS);
if (argc == 1) {
fprintf(stdout, "Usage: \n\t%s path \n\t%s url\n", argv[0], argv[0]);
fprintf(stdout, "Example: \"%s /sdcard/my.mp3\" or \"%s file:///sdcard/my.mp3\"\n",
argv[0], argv[0]);
exit(EXIT_FAILURE);
}
SLEngineOption EngineOption[] = {
{(SLuint32) SL_ENGINEOPTION_THREADSAFE,
(SLuint32) SL_BOOLEAN_TRUE}};
res = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
CheckErr(res);
/* Realizing the SL Engine in synchronous mode. */
res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
CheckErr(res);
TestLoopUri(sl, argv[1]);
/* Shutdown OpenSL ES */
(*sl)->Destroy(sl);
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,344 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
//#include <sys/time.h>
#include <SLES/OpenSLES.h>
#define MAX_NUMBER_INTERFACES 2
#define MAX_NUMBER_PLAYERS 40
#define PREFETCHEVENT_ERROR_CANDIDATE \
(SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE)
/* the OpenSL ES engine from which we create all other resources */
SLObjectItf slEngine;
SLEngineItf engineItf;
SLObjectItf outputMix;
SLboolean required[MAX_NUMBER_INTERFACES];
SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
SLObjectItf audioPlayer[MAX_NUMBER_PLAYERS];
bool validplayer[MAX_NUMBER_PLAYERS];
int playerNum[MAX_NUMBER_PLAYERS];
SLPlayItf playItfs[MAX_NUMBER_PLAYERS];
SLVolumeItf volItfs[MAX_NUMBER_PLAYERS];
SLPrefetchStatusItf prefetchItfs[MAX_NUMBER_PLAYERS];
SLDataSource audioSource;
SLDataLocator_URI uri;
SLDataFormat_MIME mime;
SLDataSink audioSink;
SLDataLocator_OutputMix locator_outputmix;
//-----------------------------------------------------------------
//* Exits the application if an error is encountered */
#define CheckErr(x) ExitOnErrorFunc(x, -1, __LINE__)
#define CheckErrPlyr(x, id) ExitOnErrorFunc(x, id, __LINE__)
void ExitOnErrorFunc( SLresult result, int playerId, int line)
{
if (SL_RESULT_SUCCESS != result) {
if (playerId == -1) {
fprintf(stderr, "Error %u code encountered at line %d, exiting\n", result, line);
} else {
fprintf(stderr, "Error %u code encountered at line %d for player %d, exiting\n",
result, line, playerId);
}
exit(EXIT_FAILURE);
}
}
//-----------------------------------------------------------------
/* PrefetchStatusItf callback for an audio player */
void PrefetchEventCallback( SLPrefetchStatusItf caller, void *pContext, SLuint32 event)
{
SLresult res;
SLpermille level = 0;
int* pPlayerId = (int*)pContext;
res = (*caller)->GetFillLevel(caller, &level); CheckErrPlyr(res, *pPlayerId);
SLuint32 status;
//fprintf(stdout, "PrefetchEventCallback: received event %u\n", event);
res = (*caller)->GetPrefetchStatus(caller, &status); CheckErrPlyr(res, *pPlayerId);
if ((PREFETCHEVENT_ERROR_CANDIDATE == (event & PREFETCHEVENT_ERROR_CANDIDATE))
&& (level == 0) && (status == SL_PREFETCHSTATUS_UNDERFLOW)) {
fprintf(stdout, "PrefetchEventCallback: Error while prefetching data for player %d, "
"exiting\n", *pPlayerId);
exit(EXIT_FAILURE);
}
if (event & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
fprintf(stdout, "PrefetchEventCallback: Buffer fill level is = %d for player %d\n",
level, *pPlayerId);
}
if (event & SL_PREFETCHEVENT_STATUSCHANGE) {
fprintf(stdout, "PrefetchEventCallback: Prefetch Status is = %u for player %d\n",
status, *pPlayerId);
}
}
//-----------------------------------------------------------------
/* PlayItf callback for playback events */
void PlayEventCallback(
SLPlayItf caller,
void *pContext,
SLuint32 event)
{
SLresult res;
int* pPlayerId = (int*)pContext;
if (SL_PLAYEVENT_HEADATEND & event) {
fprintf(stdout, "SL_PLAYEVENT_HEADATEND reached for player %d\n", *pPlayerId);
//SignalEos();
}
if (SL_PLAYEVENT_HEADATNEWPOS & event) {
SLmillisecond pMsec = 0;
res = (*caller)->GetPosition(caller, &pMsec); CheckErrPlyr(res, *pPlayerId);
fprintf(stdout, "SL_PLAYEVENT_HEADATNEWPOS current position=%ums for player %d\n",
pMsec, *pPlayerId);
}
if (SL_PLAYEVENT_HEADATMARKER & event) {
SLmillisecond pMsec = 0;
res = (*caller)->GetPosition(caller, &pMsec); CheckErrPlyr(res, *pPlayerId);
fprintf(stdout, "SL_PLAYEVENT_HEADATMARKER current position=%ums for player %d\n",
pMsec, *pPlayerId);
}
}
//-----------------------------------------------------------------
void TestSetup(const char* path) {
SLresult res;
/* Create the engine */
SLEngineOption EngineOption[] = {
{(SLuint32) SL_ENGINEOPTION_THREADSAFE,
(SLuint32) SL_BOOLEAN_TRUE}};
res = slCreateEngine( &slEngine, 1, EngineOption, 0, NULL, NULL);
CheckErr(res);
/* Realizing the SL Engine in synchronous mode. */
res = (*slEngine)->Realize(slEngine, SL_BOOLEAN_FALSE);
CheckErr(res);
/* Get the SL Engine Interface which is implicit */
res = (*slEngine)->GetInterface(slEngine, SL_IID_ENGINE, (void*)&engineItf);
CheckErr(res);
/* Create Output Mix object to be used by player */
res = (*engineItf)->CreateOutputMix(engineItf, &outputMix, 0,
iidArray, required); CheckErr(res);
/* Realizing the Output Mix object in synchronous mode. */
res = (*outputMix)->Realize(outputMix, SL_BOOLEAN_FALSE);
CheckErr(res);
/* Setup the data source structure for the URI */
// the syntax below is more future-proof than the individual field initialization
// with regards to OpenSL ES 1.1 but adds scary compilation warnings
//uri = { SL_DATALOCATOR_URI /*locatorType*/, (SLchar*) path /*URI*/ };
//mime = { /*formatType*/ SL_DATAFORMAT_MIME, /*mimeType*/ (SLchar*)NULL,
// /*containerType*/ SL_CONTAINERTYPE_UNSPECIFIED };
uri.locatorType = SL_DATALOCATOR_URI;
uri.URI = (SLchar*) path;
mime.formatType = SL_DATAFORMAT_MIME;
mime.mimeType = (SLchar*)NULL;
mime.containerType = SL_CONTAINERTYPE_UNSPECIFIED;
audioSource.pFormat = (void *)&mime;
audioSource.pLocator = (void *)&uri;
/* Setup the data sink structure */
locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX;
locator_outputmix.outputMix = outputMix;
audioSink.pLocator = (void *)&locator_outputmix;
audioSink.pFormat = NULL;
/* Initialize arrays required[] and iidArray[] */
for (int i=0 ; i < MAX_NUMBER_INTERFACES ; i++) {
required[i] = SL_BOOLEAN_FALSE;
iidArray[i] = SL_IID_NULL;
}
/* Set arrays required[] and iidArray[] for VOLUME and PREFETCHSTATUS interface */
required[0] = SL_BOOLEAN_TRUE;
iidArray[0] = SL_IID_VOLUME;
required[1] = SL_BOOLEAN_TRUE;
iidArray[1] = SL_IID_PREFETCHSTATUS;
fprintf(stdout, "TestSetup(%s) completed\n", path);
}
//-----------------------------------------------------------------
void TestTeardown() {
/* Destroy Output Mix object */
(*outputMix)->Destroy(outputMix);
/* Shutdown OpenSL ES */
(*slEngine)->Destroy(slEngine);
}
//-----------------------------------------------------------------
/**
* Create a player and, if the creation is successful,
* configure it, and start playing.
*/
void CreatePlayer(int playerId) {
SLresult res;
playerNum[playerId] = playerId;
/* Create the audio player */
res = (*engineItf)->CreateAudioPlayer(engineItf, &audioPlayer[playerId],
&audioSource, &audioSink, MAX_NUMBER_INTERFACES, iidArray, required);
if (SL_RESULT_SUCCESS != res) {
// do not abort the test, just flag the player as not a candidate for destruction
fprintf(stdout, "CreateAudioPlayer for player %d failed\n", playerId);
validplayer[playerId] = false;
return;
}
validplayer[playerId] = true;
/* Realizing the player in synchronous mode. */
res = (*audioPlayer[playerId])->Realize(audioPlayer[playerId], SL_BOOLEAN_FALSE);
if (SL_RESULT_SUCCESS != res) {
// do not abort the test, just stop the player initialization here
fprintf(stdout, "Realize for player %d failed\n", playerId);
// this player is still a candidate for destruction
return;
}
// after this point, any failure is a test failure
/* Get interfaces */
res = (*audioPlayer[playerId])->GetInterface(audioPlayer[playerId], SL_IID_PLAY,
(void*)&playItfs[playerId]);
CheckErrPlyr(res, playerId);
res = (*audioPlayer[playerId])->GetInterface(audioPlayer[playerId], SL_IID_VOLUME,
(void*)&volItfs[playerId]);
CheckErrPlyr(res, playerId);
res = (*audioPlayer[playerId])->GetInterface(audioPlayer[playerId], SL_IID_PREFETCHSTATUS,
(void*)&prefetchItfs[playerId]);
CheckErrPlyr(res, playerId);
res = (*prefetchItfs[playerId])->RegisterCallback(prefetchItfs[playerId], PrefetchEventCallback,
&playerNum[playerId]);
CheckErrPlyr(res, playerId);
res = (*prefetchItfs[playerId])->SetCallbackEventsMask(prefetchItfs[playerId],
SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE);
CheckErrPlyr(res, playerId);
/* Set the player volume */
res = (*volItfs[playerId])->SetVolumeLevel( volItfs[playerId], -300);
CheckErrPlyr(res, playerId);
/* Set up the player callback to get events during the decoding */
res = (*playItfs[playerId])->SetMarkerPosition(playItfs[playerId], 2000);
CheckErrPlyr(res, playerId);
res = (*playItfs[playerId])->SetPositionUpdatePeriod(playItfs[playerId], 500);
CheckErrPlyr(res, playerId);
res = (*playItfs[playerId])->SetCallbackEventsMask(playItfs[playerId],
SL_PLAYEVENT_HEADATMARKER | SL_PLAYEVENT_HEADATNEWPOS | SL_PLAYEVENT_HEADATEND);
CheckErrPlyr(res, playerId);
res = (*playItfs[playerId])->RegisterCallback(playItfs[playerId], PlayEventCallback,
&playerNum[playerId]);
CheckErrPlyr(res, playerId);
/* Configure fill level updates every 5 percent */
(*prefetchItfs[playerId])->SetFillUpdatePeriod(prefetchItfs[playerId], 50);
/* Play the URI */
/* first cause the player to prefetch the data */
fprintf(stdout, "Setting player %d to PAUSED\n", playerId);
res = (*playItfs[playerId])->SetPlayState( playItfs[playerId], SL_PLAYSTATE_PAUSED );
CheckErrPlyr(res, playerId);
/* wait until there's data to play */
SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW;
SLuint32 timeOutIndex = 10; // 1s, should be enough for a local file
while ((prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) && (timeOutIndex > 0)) {
usleep(100 * 1000);
res = (*prefetchItfs[playerId])->GetPrefetchStatus(prefetchItfs[playerId], &prefetchStatus);
CheckErrPlyr(res, playerId);
timeOutIndex--;
}
if (timeOutIndex == 0) {
fprintf(stderr, "Prefetch timed out for player %d\n", playerId);
return;
}
res = (*playItfs[playerId])->SetPlayState( playItfs[playerId], SL_PLAYSTATE_PLAYING );
CheckErrPlyr(res, playerId);
/* Display duration */
SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
res = (*playItfs[playerId])->GetDuration(playItfs[playerId], &durationInMsec);
CheckErrPlyr(res, playerId);
if (durationInMsec == SL_TIME_UNKNOWN) {
fprintf(stdout, "Content duration is unknown for player %d\n", playerId);
} else {
fprintf(stdout, "Content duration is %u ms for player %d\n", durationInMsec, playerId);
}
}
//-----------------------------------------------------------------
void DestroyPlayer(int playerId) {
fprintf(stdout, "About to destroy player %d\n", playerId);
/* Destroy the player */
(*audioPlayer[playerId])->Destroy(audioPlayer[playerId]);
}
//-----------------------------------------------------------------
int main(int argc, char* const argv[])
{
fprintf(stdout, "OpenSL ES test %s: creates and destroys as many ", argv[0]);
fprintf(stdout, "AudioPlayer objects as possible (max=%d)\n\n", MAX_NUMBER_PLAYERS);
if (argc == 1) {
fprintf(stdout, "Usage: %s path \n\t%s url\n", argv[0], argv[0]);
fprintf(stdout, "Example: \"%s /sdcard/my.mp3\" or \"%s file:///sdcard/my.mp3\"\n",
argv[0], argv[0]);
exit(EXIT_FAILURE);
}
TestSetup(argv[1]);
for (int i=0 ; i<MAX_NUMBER_PLAYERS ; i++) {
CreatePlayer(i);
}
fprintf(stdout, "After creating %d AudioPlayers\n", MAX_NUMBER_PLAYERS);
/* Wait for an arbitrary amount of time. if playing a long file, the players will still
be playing while the destructions start. */
usleep(10*1000*1000); // 10s
for (int i=0 ; i<MAX_NUMBER_PLAYERS ; i++) {
if (validplayer[i]) {
DestroyPlayer(i);
}
}
fprintf(stdout, "After destroying valid players among %d AudioPlayers\n", MAX_NUMBER_PLAYERS);
TestTeardown();
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,271 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <SLES/OpenSLES.h>
#ifdef ANDROID
#include <SLES/OpenSLES_Android.h>
#endif
#define MAX_NUMBER_INTERFACES 2
//-----------------------------------------------------------------
/* Exits the application if an error is encountered */
#define ExitOnError(x) ExitOnErrorFunc(x,__LINE__)
void ExitOnErrorFunc( SLresult result , int line)
{
if (SL_RESULT_SUCCESS != result) {
fprintf(stdout, "%u error code encountered at line %d, exiting\n", result, line);
exit(EXIT_FAILURE);
}
}
//-----------------------------------------------------------------
/* Play an audio URIs on the given stream type */
void TestStreamTypeConfiguration( SLObjectItf sl, const char* path, const SLint32 type)
{
SLresult result;
SLEngineItf EngineItf;
/* Objects this application uses: one player and an ouput mix */
SLObjectItf player, outputMix;
/* Source of audio data to play */
SLDataSource audioSource;
SLDataLocator_URI uri;
SLDataFormat_MIME mime;
/* Data sinks for the audio player */
SLDataSink audioSink;
SLDataLocator_OutputMix locator_outputmix;
/* Play, Volume and AndroidStreamType interfaces for the audio player */
SLPlayItf playItf;
SLPrefetchStatusItf prefetchItf;
#ifdef ANDROID
SLAndroidConfigurationItf configItf;
#endif
SLboolean required[MAX_NUMBER_INTERFACES];
SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
/* Get the SL Engine Interface which is implicit */
result = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);
ExitOnError(result);
/* Initialize arrays required[] and iidArray[] */
for (int i=0 ; i < MAX_NUMBER_INTERFACES ; i++) {
required[i] = SL_BOOLEAN_FALSE;
iidArray[i] = SL_IID_NULL;
}
/* ------------------------------------------------------ */
/* Configuration of the output mix */
/* Create Output Mix object to be used by the player */
result = (*EngineItf)->CreateOutputMix(EngineItf, &outputMix, 0, iidArray, required);
ExitOnError(result);
/* Realize the Output Mix object in synchronous mode */
result = (*outputMix)->Realize(outputMix, SL_BOOLEAN_FALSE);
ExitOnError(result);
/* Setup the data sink structure */
locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX;
locator_outputmix.outputMix = outputMix;
audioSink.pLocator = (void*)&locator_outputmix;
audioSink.pFormat = NULL;
/* ------------------------------------------------------ */
/* Configuration of the player */
/* Set arrays required[] and iidArray[] for SLAndroidConfigurationItf interfaces */
/* (SLPlayItf is implicit) */
required[0] = SL_BOOLEAN_TRUE;
iidArray[0] = SL_IID_PREFETCHSTATUS;
#ifdef ANDROID
required[1] = SL_BOOLEAN_TRUE;
iidArray[1] = SL_IID_ANDROIDCONFIGURATION;
#endif
/* Setup the data source structure for the URI */
uri.locatorType = SL_DATALOCATOR_URI;
uri.URI = (SLchar*) path;
mime.formatType = SL_DATAFORMAT_MIME;
/* this is how ignored mime information is specified, according to OpenSL ES spec
* in 9.1.6 SLDataFormat_MIME and 8.23 SLMetadataTraversalItf GetChildInfo */
mime.mimeType = (SLchar*)NULL;
mime.containerType = SL_CONTAINERTYPE_UNSPECIFIED;
audioSource.pFormat = (void*)&mime;
audioSource.pLocator = (void*)&uri;
/* Create the audio player */
result = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink,
MAX_NUMBER_INTERFACES, iidArray, required);
ExitOnError(result);
/* Retrieve the configuration interface before the player is realized so its resources
* can be configured.
*/
#ifdef ANDROID
result = (*player)->GetInterface(player, SL_IID_ANDROIDCONFIGURATION, (void*)&configItf);
ExitOnError(result);
/* Set the Android audio stream type on the player */
result = (*configItf)->SetConfiguration(configItf,
SL_ANDROID_KEY_STREAM_TYPE, &type, sizeof(SLint32));
if (SL_RESULT_PARAMETER_INVALID == result) {
fprintf(stderr, "invalid stream type %d\n", type);
} else {
ExitOnError(result);
}
#endif
/* Realize the player in synchronous mode. */
result = (*player)->Realize(player, SL_BOOLEAN_FALSE); ExitOnError(result);
fprintf(stdout, "URI example: after Realize\n");
/* Get the SLPlayItf, SLPrefetchStatusItf and SLAndroidConfigurationItf interfaces for player */
result = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf);
ExitOnError(result);
result = (*player)->GetInterface(player, SL_IID_PREFETCHSTATUS, (void*)&prefetchItf);
ExitOnError(result);
fprintf(stdout, "Player configured\n");
/* ------------------------------------------------------ */
/* Playback and test */
/* Start the data prefetching by setting the player to the paused state */
result = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED );
ExitOnError(result);
/* Wait until there's data to play */
SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW;
while (prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) {
usleep(100 * 1000);
(*prefetchItf)->GetPrefetchStatus(prefetchItf, &prefetchStatus);
ExitOnError(result);
}
/* Get duration */
SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
result = (*playItf)->GetDuration(playItf, &durationInMsec);
ExitOnError(result);
if (durationInMsec == SL_TIME_UNKNOWN) {
durationInMsec = 5000;
}
/* Start playback */
result = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING );
ExitOnError(result);
usleep((durationInMsec/2) * 1000);
#ifdef ANDROID
/* Get the stream type during playback */
SLint32 currentType = -1;
SLuint32 valueSize = sizeof(SLint32) * 2; // trying too big on purpose
result = (*configItf)->GetConfiguration(configItf,
SL_ANDROID_KEY_STREAM_TYPE, &valueSize, NULL);
ExitOnError(result);
if (valueSize != sizeof(SLint32)) {
fprintf(stderr, "ERROR: size for stream type is %u, should be %zu\n",
valueSize, sizeof(SLint32));
}
result = (*configItf)->GetConfiguration(configItf,
SL_ANDROID_KEY_STREAM_TYPE, &valueSize, &currentType);
ExitOnError(result);
if (currentType != type) {
fprintf(stderr, "ERROR: stream type is %u, should be %u\n", currentType, type);
}
#endif
usleep((durationInMsec/2) * 1000);
/* Make sure player is stopped */
fprintf(stdout, "Stopping playback\n");
result = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
ExitOnError(result);
#ifdef ANDROID
/* Try again to get the stream type, just in case it changed behind our back */
result = (*configItf)->GetConfiguration(configItf,
SL_ANDROID_KEY_STREAM_TYPE, &valueSize, &currentType);
ExitOnError(result);
if (currentType != type) {
fprintf(stderr, "ERROR: stream type is %u, should be %u\n", currentType, type);
}
#endif
/* Destroy the player */
(*player)->Destroy(player);
/* Destroy Output Mix object */
(*outputMix)->Destroy(outputMix);
}
//-----------------------------------------------------------------
int main(int argc, char* const argv[])
{
SLresult result;
SLObjectItf sl;
fprintf(stdout, "OpenSL ES test %s: exercises SLPlayItf, SLAndroidConfigurationItf\n",
argv[0]);
fprintf(stdout, "and AudioPlayer with SLDataLocator_URI source / OutputMix sink\n");
fprintf(stdout, "Plays a sound on the specified android stream type\n");
if (argc < 3) {
fprintf(stdout, "Usage: \t%s url stream_type\n", argv[0]);
fprintf(stdout, " where stream_type is one of the SL_ANDROID_STREAM_ constants.\n");
fprintf(stdout, "Example: \"%s /sdcard/my.mp3 5\" \n", argv[0]);
fprintf(stdout, "Stream type %d is the default (media or music), %d is notifications\n",
SL_ANDROID_STREAM_MEDIA, SL_ANDROID_STREAM_NOTIFICATION);
return EXIT_FAILURE;
}
SLEngineOption EngineOption[] = {
{(SLuint32) SL_ENGINEOPTION_THREADSAFE, (SLuint32) SL_BOOLEAN_TRUE}
};
result = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
ExitOnError(result);
/* Realizing the SL Engine in synchronous mode. */
result = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
ExitOnError(result);
TestStreamTypeConfiguration(sl, argv[1], (SLint32)atoi(argv[2]));
/* Shutdown OpenSL ES */
(*sl)->Destroy(sl);
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,352 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (c) 2009 The Khronos Group Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and /or associated documentation files (the "Materials "), to deal in the
* Materials without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Materials,
* and to permit persons to whom the Materials are furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Materials.
*
* THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS IN THE
* MATERIALS.
*/
#include <stdlib.h>
#include <stdio.h>
//#include <string.h>
#include <unistd.h>
//#include <sys/time.h>
#include <SLES/OpenSLES.h>
//#define TEST_VOLUME_ITF
//#define TEST_COLD_START
#define MAX_NUMBER_INTERFACES 2
#define PREFETCHEVENT_ERROR_CANDIDATE \
(SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE)
//-----------------------------------------------------------------
//* Exits the application if an error is encountered */
#define CheckErr(x) ExitOnErrorFunc(x,__LINE__)
void ExitOnErrorFunc( SLresult result , int line)
{
if (SL_RESULT_SUCCESS != result) {
fprintf(stderr, "%u error code encountered at line %d, exiting\n", result, line);
exit(EXIT_FAILURE);
}
}
bool prefetchError = false;
//-----------------------------------------------------------------
/* PrefetchStatusItf callback for an audio player */
void PrefetchEventCallback( SLPrefetchStatusItf caller, void *pContext __unused, SLuint32 event)
{
SLpermille level = 0;
SLresult result;
result = (*caller)->GetFillLevel(caller, &level);
CheckErr(result);
SLuint32 status;
//fprintf(stdout, "PrefetchEventCallback: received event %u\n", event);
result = (*caller)->GetPrefetchStatus(caller, &status);
CheckErr(result);
if ((PREFETCHEVENT_ERROR_CANDIDATE == (event & PREFETCHEVENT_ERROR_CANDIDATE))
&& (level == 0) && (status == SL_PREFETCHSTATUS_UNDERFLOW)) {
fprintf(stdout, "PrefetchEventCallback: Error while prefetching data, exiting\n");
prefetchError = true;
}
if (event & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
fprintf(stdout, "PrefetchEventCallback: Buffer fill level is = %d\n", level);
}
if (event & SL_PREFETCHEVENT_STATUSCHANGE) {
fprintf(stdout, "PrefetchEventCallback: Prefetch Status is = %u\n", status);
}
}
//-----------------------------------------------------------------
/* PlayItf callback for playback events */
void PlayEventCallback(
SLPlayItf caller,
void *pContext __unused,
SLuint32 event)
{
if (SL_PLAYEVENT_HEADATEND & event) {
fprintf(stdout, "SL_PLAYEVENT_HEADATEND reached\n");
//SignalEos();
}
if (SL_PLAYEVENT_HEADATNEWPOS & event) {
SLmillisecond pMsec = 0;
(*caller)->GetPosition(caller, &pMsec);
fprintf(stdout, "SL_PLAYEVENT_HEADATNEWPOS current position=%ums\n", pMsec);
}
if (SL_PLAYEVENT_HEADATMARKER & event) {
SLmillisecond pMsec = 0;
(*caller)->GetPosition(caller, &pMsec);
fprintf(stdout, "SL_PLAYEVENT_HEADATMARKER current position=%ums\n", pMsec);
}
}
//-----------------------------------------------------------------
/* Play some music from a URI */
void TestPlayUri( SLObjectItf sl, const char* path)
{
SLEngineItf EngineItf;
SLresult res;
SLDataSource audioSource;
SLDataLocator_URI uri;
SLDataFormat_MIME mime;
SLDataSink audioSink;
SLDataLocator_OutputMix locator_outputmix;
SLObjectItf player;
SLPlayItf playItf;
SLVolumeItf volItf;
SLPrefetchStatusItf prefetchItf;
SLObjectItf OutputMix;
SLboolean required[MAX_NUMBER_INTERFACES];
SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
/* Get the SL Engine Interface which is implicit */
res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);
CheckErr(res);
/* Initialize arrays required[] and iidArray[] */
for (int i=0 ; i < MAX_NUMBER_INTERFACES ; i++) {
required[i] = SL_BOOLEAN_FALSE;
iidArray[i] = SL_IID_NULL;
}
// Set arrays required[] and iidArray[] for VOLUME and PREFETCHSTATUS interface
required[0] = SL_BOOLEAN_TRUE;
iidArray[0] = SL_IID_VOLUME;
required[1] = SL_BOOLEAN_TRUE;
iidArray[1] = SL_IID_PREFETCHSTATUS;
// Create Output Mix object to be used by player
res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0,
iidArray, required); CheckErr(res);
// Realizing the Output Mix object in synchronous mode.
res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE);
CheckErr(res);
/* Setup the data source structure for the URI */
uri.locatorType = SL_DATALOCATOR_URI;
uri.URI = (SLchar*) path;
mime.formatType = SL_DATAFORMAT_MIME;
mime.mimeType = (SLchar*)NULL;
mime.containerType = SL_CONTAINERTYPE_UNSPECIFIED;
audioSource.pFormat = (void *)&mime;
audioSource.pLocator = (void *)&uri;
/* Setup the data sink structure */
locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX;
locator_outputmix.outputMix = OutputMix;
audioSink.pLocator = (void *)&locator_outputmix;
audioSink.pFormat = NULL;
/* Create the audio player */
res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink,
MAX_NUMBER_INTERFACES, iidArray, required); CheckErr(res);
/* Realizing the player in synchronous mode. */
res = (*player)->Realize(player, SL_BOOLEAN_FALSE); CheckErr(res);
fprintf(stdout, "URI example: after Realize\n");
/* Get interfaces */
res = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf);
CheckErr(res);
res = (*player)->GetInterface(player, SL_IID_VOLUME, (void*)&volItf);
CheckErr(res);
res = (*player)->GetInterface(player, SL_IID_PREFETCHSTATUS, (void*)&prefetchItf);
CheckErr(res);
res = (*prefetchItf)->RegisterCallback(prefetchItf, PrefetchEventCallback, &prefetchItf);
CheckErr(res);
res = (*prefetchItf)->SetCallbackEventsMask(prefetchItf,
SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE);
CheckErr(res);
/* Configure fill level updates every 5 percent */
(*prefetchItf)->SetFillUpdatePeriod(prefetchItf, 50);
/* Set up the player callback to get events during the decoding */
res = (*playItf)->SetMarkerPosition(playItf, 2000);
CheckErr(res);
res = (*playItf)->SetPositionUpdatePeriod(playItf, 500);
CheckErr(res);
res = (*playItf)->SetCallbackEventsMask(playItf,
SL_PLAYEVENT_HEADATMARKER | SL_PLAYEVENT_HEADATNEWPOS | SL_PLAYEVENT_HEADATEND);
CheckErr(res);
res = (*playItf)->RegisterCallback(playItf, PlayEventCallback, NULL);
CheckErr(res);
/* Display duration */
SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
res = (*playItf)->GetDuration(playItf, &durationInMsec);
CheckErr(res);
if (durationInMsec == SL_TIME_UNKNOWN) {
fprintf(stdout, "Content duration is unknown (before starting to prefetch)\n");
} else {
fprintf(stdout, "Content duration is %u ms (before starting to prefetch)\n",
durationInMsec);
}
/* Set the player volume */
res = (*volItf)->SetVolumeLevel( volItf, -300);
CheckErr(res);
/* Play the URI */
/* first cause the player to prefetch the data */
fprintf(stdout, "Before set to PAUSED\n");
res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED );
fprintf(stdout, "After set to PAUSED\n");
CheckErr(res);
usleep(100 * 1000);
/* wait until there's data to play */
//SLpermille fillLevel = 0;
SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW;
SLuint32 timeOutIndex = 100; // 10s
while ((prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) && (timeOutIndex > 0) &&
!prefetchError) {
usleep(100 * 1000);
(*prefetchItf)->GetPrefetchStatus(prefetchItf, &prefetchStatus);
timeOutIndex--;
}
if (timeOutIndex == 0 || prefetchError) {
fprintf(stderr, "We\'re done waiting, failed to prefetch data in time, exiting\n");
goto destroyRes;
}
/* Display duration again, */
res = (*playItf)->GetDuration(playItf, &durationInMsec);
CheckErr(res);
if (durationInMsec == SL_TIME_UNKNOWN) {
fprintf(stdout, "Content duration is unknown (after prefetch completed)\n");
} else {
fprintf(stdout, "Content duration is %u ms (after prefetch completed)\n", durationInMsec);
}
fprintf(stdout, "URI example: starting to play\n");
res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING );
CheckErr(res);
#ifdef TEST_VOLUME_ITF
usleep(5*1000 * 1000);
fprintf(stdout, "setting vol to 0\n");
(*volItf)->SetVolumeLevel( volItf, 0);
usleep(3*1000 * 1000);
fprintf(stdout, "setting vol to -20dB\n");
(*volItf)->SetVolumeLevel( volItf, -2000);
usleep(3*1000 * 1000);
fprintf(stdout, "mute\n");
(*volItf)->SetMute( volItf, SL_BOOLEAN_TRUE);
usleep(3*1000 * 1000);
fprintf(stdout, "setting vol to 0dB while muted\n");
(*volItf)->SetVolumeLevel( volItf, 0);
usleep(3*1000 * 1000);
fprintf(stdout, "unmuting\n");
(*volItf)->SetMute( volItf, SL_BOOLEAN_FALSE);
usleep(3*1000 * 1000);
#endif
#ifndef TEST_COLD_START
usleep(durationInMsec * 1000);
#else
/* Wait as long as the duration of the content before stopping */
/* Experiment: wait for the duration + 200ms: with a cold start of the audio hardware, we */
/* won't see the SL_PLAYEVENT_HEADATEND event, due to hw wake up induced latency, but */
/* with a warm start it will be received. */
usleep((durationInMsec + 200) * 1000);
#endif
/* Make sure player is stopped */
fprintf(stdout, "URI example: stopping playback\n");
res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
CheckErr(res);
destroyRes:
/* Destroy the player */
(*player)->Destroy(player);
/* Destroy Output Mix object */
(*OutputMix)->Destroy(OutputMix);
}
//-----------------------------------------------------------------
int main(int argc, char* const argv[])
{
SLresult res;
SLObjectItf sl;
fprintf(stdout, "OpenSL ES test %s: exercises SLPlayItf, SLVolumeItf ", argv[0]);
fprintf(stdout, "and AudioPlayer with SLDataLocator_URI source / OutputMix sink\n");
fprintf(stdout, "Plays a sound and stops after its reported duration\n\n");
if (argc == 1) {
fprintf(stdout, "Usage: %s path \n\t%s url\n", argv[0], argv[0]);
fprintf(stdout, "Example: \"%s /sdcard/my.mp3\" or \"%s file:///sdcard/my.mp3\"\n",
argv[0], argv[0]);
exit(EXIT_FAILURE);
}
SLEngineOption EngineOption[] = {
{(SLuint32) SL_ENGINEOPTION_THREADSAFE,
(SLuint32) SL_BOOLEAN_TRUE}};
res = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
CheckErr(res);
/* Realizing the SL Engine in synchronous mode. */
res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
CheckErr(res);
TestPlayUri(sl, argv[1]);
/* Shutdown OpenSL ES */
(*sl)->Destroy(sl);
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,288 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <SLES/OpenSLES.h>
#define MAX_NUMBER_INTERFACES 3
//-----------------------------------------------------------------
/* Exits the application if an error is encountered */
void ExitOnError( SLresult result )
{
if (SL_RESULT_SUCCESS != result) {
fprintf(stdout, "%u error code encountered, exiting\n", result);
exit(EXIT_FAILURE);
}
}
//-----------------------------------------------------------------
/* PlayItf callback for an audio player */
void PlayEventCallback( SLPlayItf caller __unused, void *pContext __unused, SLuint32 event)
{
fprintf(stdout, "PlayEventCallback event = ");
if (event & SL_PLAYEVENT_HEADATEND) {
fprintf(stdout, "SL_PLAYEVENT_HEADATEND ");
}
if (event & SL_PLAYEVENT_HEADATMARKER) {
fprintf(stdout, "SL_PLAYEVENT_HEADATMARKER ");
}
if (event & SL_PLAYEVENT_HEADATNEWPOS) {
fprintf(stdout, "SL_PLAYEVENT_HEADATNEWPOS ");
}
if (event & SL_PLAYEVENT_HEADMOVING) {
fprintf(stdout, "SL_PLAYEVENT_HEADMOVING ");
}
if (event & SL_PLAYEVENT_HEADSTALLED) {
fprintf(stdout, "SL_PLAYEVENT_HEADSTALLED");
}
fprintf(stdout, "\n");
}
//-----------------------------------------------------------------
/* Play two audio URIs, pan them left and right */
void TestPlayUri( SLObjectItf sl, const char* path, const char* path2)
{
SLresult result;
SLEngineItf EngineItf;
/* Objects this application uses: two players and an ouput mix */
SLObjectItf player, player2, outputMix;
/* Source of audio data to play, we'll reuse the same source for two different players */
SLDataSource audioSource;
SLDataLocator_URI uri;
SLDataFormat_MIME mime;
/* Data sinks for the two audio players */
SLDataSink audioSink;
SLDataLocator_OutputMix locator_outputmix;
/* Play, Volume and PrefetchStatus interfaces for the audio players */
SLPlayItf playItf, playItf2;
SLVolumeItf volItf, volItf2;
SLPrefetchStatusItf prefetchItf, prefetchItf2;
SLboolean required[MAX_NUMBER_INTERFACES];
SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
/* Get the SL Engine Interface which is implicit */
result = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);
ExitOnError(result);
/* Initialize arrays required[] and iidArray[] */
for (int i=0 ; i < MAX_NUMBER_INTERFACES ; i++) {
required[i] = SL_BOOLEAN_FALSE;
iidArray[i] = SL_IID_NULL;
}
/* Set arrays required[] and iidArray[] for SLVolumeItf and SLPrefetchStatusItf interfaces */
/* (SLPlayItf is implicit) */
required[0] = SL_BOOLEAN_TRUE;
iidArray[0] = SL_IID_VOLUME;
required[1] = SL_BOOLEAN_TRUE;
iidArray[1] = SL_IID_PREFETCHSTATUS;
/* ------------------------------------------------------ */
/* Configuration of the output mix */
/* Create Output Mix object to be used each player */
result = (*EngineItf)->CreateOutputMix(EngineItf, &outputMix, 0, iidArray, required);
ExitOnError(result);
/* Realize the Output Mix object in synchronous mode */
result = (*outputMix)->Realize(outputMix, SL_BOOLEAN_FALSE);
ExitOnError(result);
/* Setup the data sink structure */
locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX;
locator_outputmix.outputMix = outputMix;
audioSink.pLocator = (void *)&locator_outputmix;
audioSink.pFormat = NULL;
/* ------------------------------------------------------ */
/* Configuration of the players */
/* Setup the data source structure for the first URI */
uri.locatorType = SL_DATALOCATOR_URI;
uri.URI = (SLchar*) path;
mime.formatType = SL_DATAFORMAT_MIME;
/* this is how ignored mime information is specified, according to OpenSL ES spec
* in 9.1.6 SLDataFormat_MIME and 8.23 SLMetadataTraversalItf GetChildInfo */
mime.mimeType = (SLchar*)NULL;
mime.containerType = SL_CONTAINERTYPE_UNSPECIFIED;
audioSource.pFormat = (void *)&mime;
audioSource.pLocator = (void *)&uri;
/* Create the first audio player */
result = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink, 2,
iidArray, required);
ExitOnError(result);
/* Create the second audio player with a different path for its data source */
uri.URI = (SLchar*) path2;
audioSource.pLocator = (void *)&uri;
result = (*EngineItf)->CreateAudioPlayer(EngineItf, &player2, &audioSource, &audioSink, 2,
iidArray, required);
ExitOnError(result);
/* Realize the players in synchronous mode. */
result = (*player)->Realize(player, SL_BOOLEAN_FALSE); ExitOnError(result);
result = (*player)->Realize(player2, SL_BOOLEAN_FALSE); ExitOnError(result);
//fprintf(stdout, "URI example: after Realize\n");
/* Get the SLPlayItf, SLVolumeItf and SLPrefetchStatusItf interfaces for each player */
result = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf);
ExitOnError(result);
result = (*player)->GetInterface(player2, SL_IID_PLAY, (void*)&playItf2);
ExitOnError(result);
result = (*player)->GetInterface(player, SL_IID_VOLUME, (void*)&volItf);
ExitOnError(result);
result = (*player2)->GetInterface(player2, SL_IID_VOLUME, (void*)&volItf2);
ExitOnError(result);
result = (*player)->GetInterface(player, SL_IID_PREFETCHSTATUS, (void*)&prefetchItf);
ExitOnError(result);
result = (*player2)->GetInterface(player2, SL_IID_PREFETCHSTATUS, (void*)&prefetchItf2);
ExitOnError(result);
/* Setup to receive playback events */
result = (*playItf)->RegisterCallback(playItf, PlayEventCallback, &playItf);
ExitOnError(result);
result = (*playItf)->SetCallbackEventsMask(playItf,
SL_PLAYEVENT_HEADATEND| SL_PLAYEVENT_HEADATMARKER | SL_PLAYEVENT_HEADATNEWPOS
| SL_PLAYEVENT_HEADMOVING | SL_PLAYEVENT_HEADSTALLED);
ExitOnError(result);
/* Set the player volume */
result = (*volItf)->SetVolumeLevel( volItf, -300);
ExitOnError(result);
/* Pan the first player to the left */
result = (*volItf)->EnableStereoPosition( volItf, SL_BOOLEAN_TRUE); ExitOnError(result);
result = (*volItf)->SetStereoPosition( volItf, -1000); ExitOnError(result);
/* Pan the second player to the right */
result = (*volItf2)->EnableStereoPosition( volItf2, SL_BOOLEAN_TRUE); ExitOnError(result);
result = (*volItf2)->SetStereoPosition( volItf2, 1000); ExitOnError(result);
/* ------------------------------------------------------ */
/* Playback */
/* Start the data prefetching by setting the players to the paused state */
result = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED );
ExitOnError(result);
result = (*playItf2)->SetPlayState( playItf2, SL_PLAYSTATE_PAUSED );
ExitOnError(result);
/* wait until there's data to play */
SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW;
while (prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) {
usleep(100 * 1000);
(*prefetchItf)->GetPrefetchStatus(prefetchItf, &prefetchStatus);
}
prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW;
while (prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) {
usleep(100 * 1000);
(*prefetchItf2)->GetPrefetchStatus(prefetchItf2, &prefetchStatus);
}
result = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING );
ExitOnError(result);
/* Wait 2s before starting the second player */
usleep(2000 * 1000);
fprintf(stdout, "URI example: starting to play %s\n", path2);
result = (*playItf2)->SetPlayState( playItf2, SL_PLAYSTATE_PLAYING );
ExitOnError(result);
/* Display duration */
SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
result = (*playItf)->GetDuration(playItf, &durationInMsec);
ExitOnError(result);
if (durationInMsec == SL_TIME_UNKNOWN) {
fprintf(stdout, "Content duration of first URI is unknown\n");
} else {
fprintf(stdout, "Content duration of first URI is %u ms\n", durationInMsec);
}
/* Wait as long as the duration of the first URI + 2s before stopping */
if (durationInMsec == SL_TIME_UNKNOWN) {
durationInMsec = 5000; /* arbitrary time when duration is unknown */
}
usleep((durationInMsec + 2000) * 1000);
/* Make sure player is stopped */
fprintf(stdout, "URI example: stopping playback\n");
result = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
ExitOnError(result);
result = (*playItf2)->SetPlayState(playItf2, SL_PLAYSTATE_STOPPED);
ExitOnError(result);
/* Destroy the players */
(*player)->Destroy(player);
(*player2)->Destroy(player2);
/* Destroy Output Mix object */
(*outputMix)->Destroy(outputMix);
}
//-----------------------------------------------------------------
int main(int argc, char* const argv[])
{
SLresult result;
SLObjectItf sl;
fprintf(stdout, "OpenSL ES test %s: exercises SLPlayItf, SLVolumeItf (incl. stereo position) ",
argv[0]);
fprintf(stdout, "and AudioPlayer with SLDataLocator_URI source / OutputMix sink\n");
fprintf(stdout, "Plays two sounds (or twice the same) and pans them left and right.");
fprintf(stdout, "Stops after the end of the first + 2s\n");
if (argc == 1) {
fprintf(stdout, "Usage: \n\t%s url1 url2 \n\t%s url\n", argv[0], argv[0]);
fprintf(stdout, "Example: \"%s /sdcard/my.mp3 http://blabla/my.wav\" ", argv[0]);
fprintf(stdout, "or \"%s file:///sdcard/my.mp3\"\n", argv[0]);
exit(EXIT_FAILURE);
}
SLEngineOption EngineOption[] = {
{(SLuint32) SL_ENGINEOPTION_THREADSAFE, (SLuint32) SL_BOOLEAN_TRUE}
};
result = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
ExitOnError(result);
/* Realizing the SL Engine in synchronous mode. */
result = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
ExitOnError(result);
if (argc == 2) {
TestPlayUri(sl, argv[1], argv[1]);
} else if (argc == 3) {
TestPlayUri(sl, argv[1], argv[2]);
}
/* Shutdown OpenSL ES */
(*sl)->Destroy(sl);
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,427 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <assert.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <SLES/OpenSLES.h>
#define MAX_NUMBER_INTERFACES 3
#define REPETITIONS 4 // 4 repetitions, but will stop the looping before the end
#define INITIAL_RATE 2000 // 2x normal playback speed
// These are extensions to OpenSL ES 1.0.1 values
#define SL_PREFETCHSTATUS_UNKNOWN 0
#define SL_PREFETCHSTATUS_ERROR ((SLuint32) -1)
// Mutex and condition shared with main program to protect prefetch_status
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
SLuint32 prefetch_status = SL_PREFETCHSTATUS_UNKNOWN;
/* used to detect errors likely to have occured when the OpenSL ES framework fails to open
* a resource, for instance because a file URI is invalid, or an HTTP server doesn't respond.
*/
#define PREFETCHEVENT_ERROR_CANDIDATE \
(SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE)
//-----------------------------------------------------------------
//* Exits the application if an error is encountered */
#define CheckErr(x) ExitOnErrorFunc(x,__LINE__)
void ExitOnErrorFunc( SLresult result , int line)
{
if (SL_RESULT_SUCCESS != result) {
fprintf(stderr, "%u error code encountered at line %d, exiting\n", result, line);
exit(EXIT_FAILURE);
}
}
//-----------------------------------------------------------------
/* PlayItf callback for an audio player */
void PlayEventCallback( SLPlayItf caller __unused, void *pContext, SLuint32 event)
{
fprintf(stdout, "PlayEventCallback event = ");
if (event & SL_PLAYEVENT_HEADATEND) {
fprintf(stdout, "SL_PLAYEVENT_HEADATEND \n");
/* slow playback down by 2x for next loop, if possible */
SLpermille minRate, maxRate, stepSize, rate = 1000;
SLuint32 capa;
assert(NULL != pContext);
SLPlaybackRateItf pRateItf = (SLPlaybackRateItf)pContext;
SLresult res = (*pRateItf)->GetRate(pRateItf, &rate); CheckErr(res);
res = (*pRateItf)->GetRateRange(pRateItf, 0, &minRate, &maxRate, &stepSize, &capa);
CheckErr(res);
fprintf(stdout, "old rate = %d, minRate=%d, maxRate=%d\n", rate, minRate, maxRate);
rate /= 2;
if (rate < minRate) {
rate = minRate;
}
fprintf(stdout, "new rate = %d\n", rate);
res = (*pRateItf)->SetRate(pRateItf, rate); CheckErr(res);
if (res == SL_RESULT_FEATURE_UNSUPPORTED) {
fprintf(stderr, "new playback rate %d per mille is unsupported\n", rate);
} else {
CheckErr(res);
}
}
if (event & SL_PLAYEVENT_HEADATMARKER) {
fprintf(stdout, "SL_PLAYEVENT_HEADATMARKER ");
}
if (event & SL_PLAYEVENT_HEADATNEWPOS) {
fprintf(stdout, "SL_PLAYEVENT_HEADATNEWPOS ");
}
if (event & SL_PLAYEVENT_HEADMOVING) {
fprintf(stdout, "SL_PLAYEVENT_HEADMOVING ");
}
if (event & SL_PLAYEVENT_HEADSTALLED) {
fprintf(stdout, "SL_PLAYEVENT_HEADSTALLED");
}
fprintf(stdout, "\n");
}
//-----------------------------------------------------------------
/* PrefetchStatusItf callback for an audio player */
void PrefetchEventCallback( SLPrefetchStatusItf caller, void *pContext, SLuint32 event)
{
//fprintf(stdout, "\t\tPrefetchEventCallback: received event %u\n", event);
SLresult result;
assert(pContext == NULL);
SLpermille level = 0;
result = (*caller)->GetFillLevel(caller, &level);
CheckErr(result);
SLuint32 status;
result = (*caller)->GetPrefetchStatus(caller, &status);
CheckErr(result);
if (event & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
fprintf(stdout, "\t\tPrefetchEventCallback: Buffer fill level is = %d\n", level);
}
if (event & SL_PREFETCHEVENT_STATUSCHANGE) {
fprintf(stdout, "\t\tPrefetchEventCallback: Prefetch Status is = %u\n", status);
}
SLuint32 new_prefetch_status;
if ((event & PREFETCHEVENT_ERROR_CANDIDATE) == PREFETCHEVENT_ERROR_CANDIDATE
&& level == 0 && status == SL_PREFETCHSTATUS_UNDERFLOW) {
fprintf(stdout, "\t\tPrefetchEventCallback: Error while prefetching data, exiting\n");
new_prefetch_status = SL_PREFETCHSTATUS_ERROR;
} else if (event == SL_PREFETCHEVENT_STATUSCHANGE &&
status == SL_PREFETCHSTATUS_SUFFICIENTDATA) {
new_prefetch_status = status;
} else {
return;
}
int ok;
ok = pthread_mutex_lock(&mutex);
assert(ok == 0);
prefetch_status = new_prefetch_status;
ok = pthread_cond_signal(&cond);
assert(ok == 0);
ok = pthread_mutex_unlock(&mutex);
assert(ok == 0);
}
// Display rate capabilities in a nicely formatted way
void printCapabilities(SLuint32 capabilities)
{
bool needBar = false;
printf("0x%x (", capabilities);
#define _(x) \
if (capabilities & SL_RATEPROP_##x) { \
if (needBar) \
printf("|"); \
printf("SL_RATEPROP_" #x); \
needBar = true; \
capabilities &= ~SL_RATEPROP_##x; \
}
_(SILENTAUDIO)
_(STAGGEREDAUDIO)
_(NOPITCHCORAUDIO)
_(PITCHCORAUDIO)
if (capabilities != 0) {
if (needBar)
printf("|");
printf("0x%x", capabilities);
needBar = true;
}
if (!needBar)
printf("N/A");
printf(")");
}
//-----------------------------------------------------------------
/* Play some music from a URI */
void TestSlowDownUri( SLObjectItf sl, const char* path)
{
SLEngineItf EngineItf;
SLresult res;
SLDataSource audioSource;
SLDataLocator_URI uri;
SLDataFormat_MIME mime;
SLDataSink audioSink;
SLDataLocator_OutputMix locator_outputmix;
SLObjectItf player;
SLPlayItf playItf;
SLSeekItf seekItf;
SLPrefetchStatusItf prefetchItf;
SLPlaybackRateItf rateItf;
SLObjectItf OutputMix;
SLboolean required[MAX_NUMBER_INTERFACES];
SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
/* Get the SL Engine Interface which is implicit */
res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf); CheckErr(res);
/* Initialize arrays required[] and iidArray[] */
for (int i=0 ; i < MAX_NUMBER_INTERFACES ; i++) {
required[i] = SL_BOOLEAN_FALSE;
iidArray[i] = SL_IID_NULL;
}
required[0] = SL_BOOLEAN_TRUE;
iidArray[0] = SL_IID_VOLUME;
// Create Output Mix object to be used by player
res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0,
iidArray, required); CheckErr(res);
// Realizing the Output Mix object in synchronous mode.
res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE); CheckErr(res);
/* Setup the data source structure for the URI */
uri.locatorType = SL_DATALOCATOR_URI;
uri.URI = (SLchar*) path;
mime.formatType = SL_DATAFORMAT_MIME;
mime.mimeType = (SLchar*)NULL;
mime.containerType = SL_CONTAINERTYPE_UNSPECIFIED;
audioSource.pFormat = (void *)&mime;
audioSource.pLocator = (void *)&uri;
/* Setup the data sink structure */
locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX;
locator_outputmix.outputMix = OutputMix;
audioSink.pLocator = (void *)&locator_outputmix;
audioSink.pFormat = NULL;
/******************************************************/
/* Create the audio player */
required[0] = SL_BOOLEAN_TRUE;
iidArray[0] = SL_IID_SEEK;
required[1] = SL_BOOLEAN_TRUE;
iidArray[1] = SL_IID_PREFETCHSTATUS;
required[2] = SL_BOOLEAN_TRUE;
iidArray[2] = SL_IID_PLAYBACKRATE;
res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink,
MAX_NUMBER_INTERFACES, iidArray, required); CheckErr(res);
/* Realizing the player in synchronous mode. */
res = (*player)->Realize(player, SL_BOOLEAN_FALSE); CheckErr(res);
fprintf(stdout, "URI example: after Realize\n");
/* Get interfaces */
res = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf); CheckErr(res);
res = (*player)->GetInterface(player, SL_IID_SEEK, (void*)&seekItf); CheckErr(res);
res = (*player)->GetInterface(player, SL_IID_PLAYBACKRATE, (void*)&rateItf); CheckErr(res);
res = (*player)->GetInterface(player, SL_IID_PREFETCHSTATUS, (void*)&prefetchItf);
CheckErr(res);
res = (*prefetchItf)->RegisterCallback(prefetchItf, PrefetchEventCallback, NULL);
CheckErr(res);
res = (*prefetchItf)->SetCallbackEventsMask(prefetchItf,
SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE); CheckErr(res);
/* Configure fill level updates every 5 percent */
(*prefetchItf)->SetFillUpdatePeriod(prefetchItf, 50); CheckErr(res);
/* Display duration */
SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
res = (*playItf)->GetDuration(playItf, &durationInMsec); CheckErr(res);
if (durationInMsec == SL_TIME_UNKNOWN) {
fprintf(stdout, "Content duration is unknown (before starting to prefetch)\n");
} else {
fprintf(stdout, "Content duration is %u ms (before starting to prefetch)\n",
durationInMsec);
}
/* Loop on the whole of the content */
res = (*seekItf)->SetLoop(seekItf, SL_BOOLEAN_TRUE, 0, SL_TIME_UNKNOWN); CheckErr(res);
/* Set up marker and position callbacks */
res = (*playItf)->RegisterCallback(playItf, PlayEventCallback, (void *) rateItf);
CheckErr(res);
res = (*playItf)->SetCallbackEventsMask(playItf,
SL_PLAYEVENT_HEADATEND | SL_PLAYEVENT_HEADATMARKER | SL_PLAYEVENT_HEADATNEWPOS);
res = (*playItf)->SetMarkerPosition(playItf, 1500); CheckErr(res);
res = (*playItf)->SetPositionUpdatePeriod(playItf, 500); CheckErr(res);
/* Get the default rate */
SLpermille rate = 1234;
res = (*rateItf)->GetRate(rateItf, &rate); CheckErr(res);
printf("default rate = %d per mille\n", rate);
assert(1000 == rate);
/* Get the default rate properties */
SLuint32 properties = 0;
res = (*rateItf)->GetProperties(rateItf, &properties); CheckErr(res);
printf("default rate properties: ");
printCapabilities(properties);
printf("\n");
assert(SL_RATEPROP_NOPITCHCORAUDIO == properties);
/* Get all supported playback rate ranges */
SLuint8 index;
for (index = 0; ; ++index) {
SLpermille minRate, maxRate, stepSize;
SLuint32 capabilities;
res = (*rateItf)->GetRateRange(rateItf, index, &minRate, &maxRate, &stepSize,
&capabilities);
if (res == SL_RESULT_PARAMETER_INVALID) {
if (index == 0) {
fprintf(stderr, "implementation supports no rate ranges\n");
}
break;
}
CheckErr(res);
if (index == 255) {
fprintf(stderr, "implementation supports way too many rate ranges, I'm giving up\n");
break;
}
printf("range[%u]: min=%d, max=%d, capabilities=", index, minRate, maxRate);
printCapabilities(capabilities);
printf("\n");
}
/* Change the playback rate before playback */
res = (*rateItf)->SetRate(rateItf, INITIAL_RATE);
if (res == SL_RESULT_FEATURE_UNSUPPORTED || res == SL_RESULT_PARAMETER_INVALID) {
fprintf(stderr, "initial playback rate %d per mille is unsupported\n", INITIAL_RATE);
} else {
CheckErr(res);
}
/******************************************************/
/* Play the URI */
/* first cause the player to prefetch the data */
res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED ); CheckErr(res);
// wait for prefetch status callback to indicate either sufficient data or error
pthread_mutex_lock(&mutex);
while (prefetch_status == SL_PREFETCHSTATUS_UNKNOWN) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
if (prefetch_status == SL_PREFETCHSTATUS_ERROR) {
fprintf(stderr, "Error during prefetch, exiting\n");
goto destroyRes;
}
/* Display duration again, */
res = (*playItf)->GetDuration(playItf, &durationInMsec); CheckErr(res);
if (durationInMsec == SL_TIME_UNKNOWN) {
fprintf(stdout, "Content duration is unknown (after prefetch completed)\n");
} else {
fprintf(stdout, "Content duration is %u ms (after prefetch completed)\n", durationInMsec);
}
/* Start playing */
fprintf(stdout, "starting to play\n");
res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING ); CheckErr(res);
/* Wait as long as the duration of the content, times the repetitions,
* before stopping the loop */
#if 1
usleep( (REPETITIONS-1) * durationInMsec * 1100);
#else
int ii;
for (ii = 0; ii < REPETITIONS; ++ii) {
usleep(durationInMsec * 1100);
PlayEventCallback(playItf, (void *) rateItf, SL_PLAYEVENT_HEADATEND);
}
#endif
res = (*seekItf)->SetLoop(seekItf, SL_BOOLEAN_FALSE, 0, SL_TIME_UNKNOWN); CheckErr(res);
fprintf(stdout, "As of now, stopped looping (sound shouldn't repeat from now on)\n");
/* wait some more to make sure it doesn't repeat */
usleep(durationInMsec * 1000);
/* Stop playback */
fprintf(stdout, "stopping playback\n");
res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED); CheckErr(res);
destroyRes:
/* Destroy the player */
(*player)->Destroy(player);
/* Destroy Output Mix object */
(*OutputMix)->Destroy(OutputMix);
}
//-----------------------------------------------------------------
int main(int argc, char* const argv[])
{
SLresult res;
SLObjectItf sl;
fprintf(stdout, "OpenSL ES test %s: exercises SLPlayItf, SLSeekItf, SLPlaybackRateItf\n",
argv[0]);
fprintf(stdout, "and AudioPlayer with SLDataLocator_URI source / OutputMix sink\n");
fprintf(stdout, "Plays a sound and loops it %d times while changing the \n", REPETITIONS);
fprintf(stdout, "playback rate each time.\n\n");
if (argc == 1) {
fprintf(stdout, "Usage: \n\t%s path \n\t%s url\n", argv[0], argv[0]);
fprintf(stdout, "Example: \"%s /sdcard/my.mp3\" or \"%s file:///sdcard/my.mp3\"\n",
argv[0], argv[0]);
return EXIT_FAILURE;
}
SLEngineOption EngineOption[] = {
{(SLuint32) SL_ENGINEOPTION_THREADSAFE,
(SLuint32) SL_BOOLEAN_TRUE}};
res = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
CheckErr(res);
/* Realizing the SL Engine in synchronous mode. */
res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
CheckErr(res);
TestSlowDownUri(sl, argv[1]);
/* Shutdown OpenSL ES */
(*sl)->Destroy(sl);
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,238 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <SLES/OpenSLES.h>
#define MAX_NUMBER_INTERFACES 2
#define TEST_MUTE 0
#define TEST_SOLO 1
//-----------------------------------------------------------------
/* Exits the application if an error is encountered */
#define ExitOnError(x) ExitOnErrorFunc(x,__LINE__)
void ExitOnErrorFunc( SLresult result , int line)
{
if (SL_RESULT_SUCCESS != result) {
fprintf(stdout, "%u error code encountered at line %d, exiting\n", result, line);
exit(EXIT_FAILURE);
}
}
//-----------------------------------------------------------------
/* Play an audio URIs, play, pause, stop */
void TestPlayUri( SLObjectItf sl, const char* path)
{
SLresult result;
SLEngineItf EngineItf;
/* Objects this application uses: one player and an ouput mix */
SLObjectItf player, outputMix;
/* Source of audio data to play */
SLDataSource audioSource;
SLDataLocator_URI uri;
SLDataFormat_MIME mime;
/* Data sinks for the audio player */
SLDataSink audioSink;
SLDataLocator_OutputMix locator_outputmix;
/* Play, Volume and PrefetchStatus interfaces for the audio player */
SLPlayItf playItf;
SLMuteSoloItf muteSoloItf;
SLPrefetchStatusItf prefetchItf;
SLboolean required[MAX_NUMBER_INTERFACES];
SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
/* Get the SL Engine Interface which is implicit */
result = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);
ExitOnError(result);
/* Initialize arrays required[] and iidArray[] */
for (int i=0 ; i < MAX_NUMBER_INTERFACES ; i++) {
required[i] = SL_BOOLEAN_FALSE;
iidArray[i] = SL_IID_NULL;
}
/* ------------------------------------------------------ */
/* Configuration of the output mix */
/* Create Output Mix object to be used by the player */
result = (*EngineItf)->CreateOutputMix(EngineItf, &outputMix, 0, iidArray, required);
ExitOnError(result);
/* Realize the Output Mix object in synchronous mode */
result = (*outputMix)->Realize(outputMix, SL_BOOLEAN_FALSE);
ExitOnError(result);
/* Setup the data sink structure */
locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX;
locator_outputmix.outputMix = outputMix;
audioSink.pLocator = (void*)&locator_outputmix;
audioSink.pFormat = NULL;
/* ------------------------------------------------------ */
/* Configuration of the player */
/* Set arrays required[] and iidArray[] for SLMuteSoloItf and SLPrefetchStatusItf interfaces */
/* (SLPlayItf is implicit) */
required[0] = SL_BOOLEAN_TRUE;
iidArray[0] = SL_IID_MUTESOLO;
required[1] = SL_BOOLEAN_TRUE;
iidArray[1] = SL_IID_PREFETCHSTATUS;
/* Setup the data source structure for the URI */
uri.locatorType = SL_DATALOCATOR_URI;
uri.URI = (SLchar*) path;
mime.formatType = SL_DATAFORMAT_MIME;
/* this is how ignored mime information is specified, according to OpenSL ES spec
* in 9.1.6 SLDataFormat_MIME and 8.23 SLMetadataTraversalItf GetChildInfo */
mime.mimeType = (SLchar*)NULL;
mime.containerType = SL_CONTAINERTYPE_UNSPECIFIED;
audioSource.pFormat = (void*)&mime;
audioSource.pLocator = (void*)&uri;
/* Create the audio player */
result = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink,
MAX_NUMBER_INTERFACES, iidArray, required);
ExitOnError(result);
/* Realize the player in synchronous mode. */
result = (*player)->Realize(player, SL_BOOLEAN_FALSE); ExitOnError(result);
fprintf(stdout, "URI example: after Realize\n");
/* Get the SLPlayItf, SLPrefetchStatusItf and SLMuteSoloItf interfaces for the player */
result = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf);
ExitOnError(result);
result = (*player)->GetInterface(player, SL_IID_PREFETCHSTATUS, (void*)&prefetchItf);
ExitOnError(result);
result = (*player)->GetInterface(player, SL_IID_MUTESOLO, (void*)&muteSoloItf);
ExitOnError(result);
fprintf(stdout, "Player configured\n");
/* ------------------------------------------------------ */
/* Playback and test */
/* Start the data prefetching by setting the player to the paused state */
result = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED );
ExitOnError(result);
/* Wait until there's data to play */
SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW;
while (prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) {
usleep(100 * 1000);
(*prefetchItf)->GetPrefetchStatus(prefetchItf, &prefetchStatus);
}
/* Testing play states */
/* let it play for 2s */
fprintf(stdout, "----- Playing\n");
result = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING );
ExitOnError(result);
usleep(2 * 1000 * 1000);
/* pause for 1s*/
fprintf(stdout, "----- Pausing (1s)\n");
result = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED );
ExitOnError(result);
usleep(2 * 1000 * 1000);
/* resume */
fprintf(stdout, "----- Playing (2s, should have resumed where it paused)\n");
result = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING );
ExitOnError(result);
usleep(2 * 1000 * 1000);
/* stop */
fprintf(stdout, "----- Stopping\n");
result = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
ExitOnError(result);
/* play for 2s */
fprintf(stdout, "----- Playing (2s, should have started from the beginning\n");
result = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING );
ExitOnError(result);
usleep(2 * 1000 * 1000);
/* stop */
fprintf(stdout, "----- Stopping\n");
result = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
ExitOnError(result);
/* Destroy the players */
(*player)->Destroy(player);
/* Destroy Output Mix object */
(*outputMix)->Destroy(outputMix);
}
//-----------------------------------------------------------------
int main(int argc, char* const argv[])
{
SLresult result;
SLObjectItf sl;
fprintf(stdout, "OpenSL ES test %s: exercises SLPlayItf, SLVolumeItf, SLMuteSoloItf\n",
argv[0]);
fprintf(stdout, "and AudioPlayer with SLDataLocator_URI source / OutputMix sink\n");
fprintf(stdout, "Plays a sound and alternates the muting of the channels (for 5s).\n");
fprintf(stdout, " and then alternates the solo\'ing of the channels (for 5s).\n");
fprintf(stdout, "Stops after 10s\n");
if (argc == 1) {
fprintf(stdout, "Usage: \t%s url\n", argv[0]);
fprintf(stdout, "Example: \"%s /sdcard/my.mp3\"\n", argv[0]);
exit(EXIT_FAILURE);
}
SLEngineOption EngineOption[] = {
{(SLuint32) SL_ENGINEOPTION_THREADSAFE, (SLuint32) SL_BOOLEAN_TRUE}
};
result = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
ExitOnError(result);
/* Realizing the SL Engine in synchronous mode. */
result = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
ExitOnError(result);
if (argc > 1) {
TestPlayUri(sl, argv[1]);
}
/* Shutdown OpenSL ES */
(*sl)->Destroy(sl);
return EXIT_SUCCESS;
}