Случайная папка с активами формы AudioFile
Может кто-то указать мне в правильном направлении с этим? Мне нужно получить аудиофайл случайных запросов. Я думал, что смогу сделать это, используя AssetManager, а затем использовать строковый аргумент для произвольной длины. Я получаю сообщение об ошибке на OnClickMethod. Вот код с помощью LogCat.
public class RandomSoundFormAssetsFolder extends Activity implements
OnClickListener {
/** Called when the activity is first created. */
MediaPlayer RandomAudioPlayer;
AssetFileDescriptor descriptor;
Button playSound;
String[] filelist;
AssetManager Agetlist;
String MediaFileL;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
Initialization();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void Initialization() throws IOException {
// TODO Auto-generated method stub
setContentView(R.layout.main);
playSound = (Button) findViewById(R.id.myButton);
playSound.setOnClickListener(this);
RandomAudioPlayer = new MediaPlayer();
Agetlist = this.getAssets();
filelist = Agetlist.list("");
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.myButton:
OnClickMethod();
break;
default:
break;
}
}
public class AudioRanActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
MediaPlayer RandomAudioPlayer;
AssetFileDescriptor descriptor;
Button playSound;
String[] filelist;
AssetManager Agetlist;
String MediaFileL;
int randomInt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Initialization();
}
private void Initialization() {
// TODO Auto-generated method stub
setContentView(R.layout.main);
playSound = (Button) findViewById(R.id.button1);
playSound.setOnClickListener(this);
RandomAudioPlayer = new MediaPlayer();
Log.d("In Initialization Method", "Constructor For mp");
Agetlist = this.getAssets();
try {
filelist = Agetlist.list("audio");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
OnClickMethod();
break;
default:
break;
}
}
private void OnClickMethod() {
// TODO Auto-generated method stub
Random randomGenerator = new Random();
randomInt = randomGenerator.nextInt(filelist.length);
Log.i("Length: ", String.valueOf(filelist.length));
Log.i("RanInt: ", String.valueOf(randomInt));
try {
MediaFileL = filelist[randomInt];
Log.i("LengtD: ", MediaFileL);
descriptor = getAssets().openFd(MediaFileL);
RandomAudioPlayer.setDataSource(descriptor.getFileDescriptor(),
descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
RandomAudioPlayer.prepare();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
RandomAudioPlayer.start();
Log.d("In OnClickMethod", "Start mp");
}
}
}
Журнал аварии:
05-26 17:52:51.191: W/dalvikvm(1982): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
05-26 17:52:51.282: E/AndroidRuntime(1982): FATAL EXCEPTION: main
05-26 17:52:51.282: E/AndroidRuntime(1982): java.lang.NullPointerException
05-26 17:52:51.282: E/AndroidRuntime(1982): at sound.stuff.RandomSoundFormAssetsFolder.OnClickMethod(RandomSoundFormAssetsFolder.java:68)
05-26 17:52:51.282: E/AndroidRuntime(1982): at sound.stuff.RandomSoundFormAssetsFolder.onClick(RandomSoundFormAssetsFolder.java:51)
05-26 17:52:51.282: E/AndroidRuntime(1982): at android.view.View.performClick(View.java:3511)
05-26 17:52:51.282: E/AndroidRuntime(1982): at android.view.View$PerformClick.run(View.java:14105)
05-26 17:52:51.282: E/AndroidRuntime(1982): at android.os.Handler.handleCallback(Handler.java:605)
05-26 17:52:51.282: E/AndroidRuntime(1982): at android.os.Handler.dispatchMessage(Handler.java:92)
05-26 17:52:51.282: E/AndroidRuntime(1982): at android.os.Looper.loop(Looper.java:137)
05-26 17:52:51.282: E/AndroidRuntime(1982): at android.app.ActivityThread.main(ActivityThread.java:4424)
05-26 17:52:51.282: E/AndroidRuntime(1982): at java.lang.reflect.Method.invokeNative(Native Method)
05-26 17:52:51.282: E/AndroidRuntime(1982): at java.lang.reflect.Method.invoke(Method.java:511)
05-26 17:52:51.282: E/AndroidRuntime(1982): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-26 17:52:51.282: E/AndroidRuntime(1982): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-26 17:52:51.282: E/AndroidRuntime(1982): at dalvik.system.NativeStart.main(Native Method)
Журнал аварии:
05-27 11:50:48.378: W/System.err(2512): java.io.FileNotFoundException: sounds
05-27 11:50:48.418: W/System.err(2512): at android.content.res.AssetManager.openAssetFd(Native Method)
05-27 11:50:48.418: W/System.err(2512): at android.content.res.AssetManager.openFd(AssetManager.java:331)
05-27 11:50:48.438: W/System.err(2512): at sound.stuff.RandomSoundFormAssetsFolder.OnClickMethod(RandomSoundFormAssetsFolder.java:69)
05-27 11:50:48.438: W/System.err(2512): at sound.stuff.RandomSoundFormAssetsFolder.onClick(RandomSoundFormAssetsFolder.java:53)
05-27 11:50:48.468: W/System.err(2512): at android.view.View.performClick(View.java:3511)
05-27 11:50:48.468: W/System.err(2512): at android.view.View.onKeyUp(View.java:6073)
05-27 11:50:48.468: W/System.err(2512): at android.widget.TextView.onKeyUp(TextView.java:5532)
05-27 11:50:48.488: W/System.err(2512): at android.view.KeyEvent.dispatch(KeyEvent.java:2575)
05-27 11:50:48.488: W/System.err(2512): at android.view.View.dispatchKeyEvent(View.java:5500)
05-27 11:50:48.498: W/System.err(2512): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1246)
05-27 11:50:48.498: W/System.err(2512): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1246)
05-27 11:50:48.498: W/System.err(2512): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1246)
05-27 11:50:48.508: W/System.err(2512): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1246)
05-27 11:50:48.518: W/System.err(2512): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1879)
05-27 11:50:48.518: W/System.err(2512): at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1361)
05-27 11:50:48.518: W/System.err(2512): at android.app.Activity.dispatchKeyEvent(Activity.java:2324)
05-27 11:50:48.530: W/System.err(2512): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1806)
05-27 11:50:48.538: W/System.err(2512): at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:3327)
05-27 11:50:48.538: W/System.err(2512): at android.view.ViewRootImpl.handleFinishedEvent(ViewRootImpl.java:3300)
05-27 11:50:48.558: W/System.err(2512): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2460)
05-27 11:50:48.558: W/System.err(2512): at android.os.Handler.dispatchMessage(Handler.java:99)
05-27 11:50:48.568: W/System.err(2512): at android.os.Looper.loop(Looper.java:137)
05-27 11:50:48.568: W/System.err(2512): at android.app.ActivityThread.main(ActivityThread.java:4424)
05-27 11:50:48.578: W/System.err(2512): at java.lang.reflect.Method.invokeNative(Native Method)
05-27 11:50:48.578: W/System.err(2512): at java.lang.reflect.Method.invoke(Method.java:511)
05-27 11:50:48.588: W/System.err(2512): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-27 11:50:48.600: W/System.err(2512): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-27 11:50:48.608: W/System.err(2512): at dalvik.system.NativeStart.main(Native Method)
05-27 11:50:48.608: E/MediaPlayer(2512): start called in state 1
05-27 11:50:48.608: E/MediaPlayer(2512): error (-38, 0)
05-27 11:50:48.648: E/MediaPlayer(2512): Error (-38,0)
Я работал над попыткой отладки этого. Я изменил свой код и вставил какой-то Log-метод. Строковый массив работает, я получаю длину последовательно 14, и я получаю случайную позицию. Так что все работает. Это проблема в журнале FileNotFoundException, поэтому файл не загружается, но когда я регистрирую MediaFileL, я получаю имя аудио-файла. Я использую MediaPlayer неправильно или AssetFileDescriptor? Вот код с помощью LogCat.
public class AudioRanActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
MediaPlayer RandomAudioPlayer;
AssetFileDescriptor descriptor;
Button playSound;
String[] filelist;
AssetManager Agetlist;
String MediaFileL;
int randomInt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Initialization();
}
private void Initialization() {
// TODO Auto-generated method stub
setContentView(R.layout.main);
playSound = (Button) findViewById(R.id.button1);
playSound.setOnClickListener(this);
RandomAudioPlayer = new MediaPlayer();
Log.d("In Initialization method", "RandomAudioPlayer");
Agetlist = this.getAssets();
Log.d("TAGAgetlist", "Agetlist");
try {
filelist = Agetlist.list("audio");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
OnClickMethod();
break;
default:
break;
}
}
private void OnClickMethod() {
// TODO Auto-generated method stub
Random randomGenerator = new Random();
randomInt = randomGenerator.nextInt(filelist.length);
Log.i("Lengt: ", String.valueOf(filelist.length));
Log.i("RanInt: ", String.valueOf(randomInt));
try {
MediaFileL = filelist[randomInt];
Log.i("LengtD: ", MediaFileL);
descriptor = getAssets().openFd(MediaFileL);
RandomAudioPlayer.setDataSource(descriptor.getFileDescriptor(),
descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
RandomAudioPlayer.prepare();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
RandomAudioPlayer.start();
Log.d("RanPlaystart", "RandomAudio");
}
Initialization();
}
}
Журнал:
05-28 10:12:31.175: D/In Initialization Method(792): Constructor For mp
05-28 10:13:07.606: I/Lengt:(792): 14
05-28 10:13:07.606: I/RanInt:(792): 3
05-28 10:13:07.634: I/LengtD:(792): good_job.mp3
05-28 10:13:07.655: W/System.err(792): java.io.FileNotFoundException: good_job.mp3
05-28 10:13:07.664: W/System.err(792): at android.content.res.AssetManager.openAssetFd(Native Method)
05-28 10:13:07.664: W/System.err(792): at android.content.res.AssetManager.openFd(AssetManager.java:331)
05-28 10:13:07.675: W/System.err(792): at Audio.stuff.AudioRanActivity.OnClickMethod(AudioRanActivity.java:75)
05-28 10:13:07.675: W/System.err(792): at Audio.stuff.AudioRanActivity.onClick(AudioRanActivity.java:55)
05-28 10:13:07.684: W/System.err(792): at android.view.View.performClick(View.java:3511)
05-28 10:13:07.684: W/System.err(792): at android.view.View$PerformClick.run(View.java:14105)
05-28 10:13:07.684: W/System.err(792): at android.os.Handler.handleCallback(Handler.java:605)
05-28 10:13:07.695: W/System.err(792): at android.os.Handler.dispatchMessage(Handler.java:92)
05-28 10:13:07.704: W/System.err(792): at android.os.Looper.loop(Looper.java:137)
05-28 10:13:07.716: W/System.err(792): at android.app.ActivityThread.main(ActivityThread.java:4424)
05-28 10:13:07.716: W/System.err(792): at java.lang.reflect.Method.invokeNative(Native Method)
05-28 10:13:07.716: W/System.err(792): at java.lang.reflect.Method.invoke(Method.java:511)
05-28 10:13:07.724: W/System.err(792): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-28 10:13:07.724: W/System.err(792): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-28 10:13:07.734: W/System.err(792): at dalvik.system.NativeStart.main(Native Method)
05-28 10:13:07.734: E/MediaPlayer(792): start called in state 1
05-28 10:13:07.734: E/MediaPlayer(792): error (-38, 0)
05-28 10:13:07.745: D/In OnClickMethod(792): Start mp
05-28 10:13:07.754: E/MediaPlayer(792): Error (-38,0)
3 ответа
Использование
RandomAudioPlayer = new MediaPlayer();
Agetlist = this.getAssets();
filelist = Agetlist.list("");
потому что ваш список файлов String[]; is empty.so сначала получите список всех файлов в filelist из ресурсов, затем используйте их в вашем OnClickMethod().
Вот ясный и общий метод:
private static String getRandomMediaFilePath(Context context, String assetSpecificFolderPath)
{
AssetManager assetManager;
String[] fileList;
String mediaFileName;
String mediaFilePath;
try
{
assetManager = context.getAssets();
fileList = assetManager.list(assetSpecificFolderPath);
mediaFileName = fileList[getRandomNumber(0,fileList.length - 1)];
mediaFilePath = assetSpecificFolderPath + "/" + mediaFileName;
}
catch (IOException e)
{
e.printStackTrace();
}
return mediaFilePath;
}
private static int getRandomNumber(int min, int max)
{
// Usually this should be a field rather than a method variable so
// that it is not re-seeded every call.
Random random = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = random.nextInt((max - min) + 1) + min;
return randomNum;
}
Использование:
getRandomMediaFilePath(context, "MediaResources/Sounds")
Пока папка актива содержит папку "MediaResources/Sounds"
Для тех, кто может помочь. Это работает так. Мне нужно, чтобы добавить в подпапку строку "audio/"+RandomAudio
Здесь была моя ошибка:
descriptor = getAssets().openFd("audio/" + MediaFileL);
public class AudioRanActivity extends Activity implements OnClickListener {
MediaPlayer RandomAudioPlayer;
AssetFileDescriptor descriptor;
Button playSound;
String[] filelist;
AssetManager Agetlist;
String MediaFileL;
int randomInt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Initialization();
}
private void Initialization() {
setContentView(R.layout.main);
// Geting audio-files
Agetlist = this.getAssets();
try {
// Constructs string-arry from assets/audio folder
filelist = Agetlist.list("audio");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
playSound = (Button) findViewById(R.id.button1);
playSound.setOnClickListener(this);
// MediaPlayer Constructor
RandomAudioPlayer = new MediaPlayer();
Log.d("In OnClickMethod Method TagLog", "Constructor For mp");
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
OnClickMethod();
break;
default:
break;
}
}
private void OnClickMethod() {
// Random-factory
Random randomGenerator = new Random();
// Gets int file-list length
randomInt = randomGenerator.nextInt(filelist.length);
Log.i("Length Log: ", String.valueOf(filelist.length));
Log.i("RanInt Log: ", String.valueOf(randomInt));
try {
// One Audio-file putIn string
// InputRaw = openFileInput(name)
MediaFileL = filelist[randomInt];
Log.i("What file is it? Log: ", MediaFileL);
// AssetFileDescriptor open audio-file
descriptor = getAssets().openFd("audio/" + MediaFileL);
/*
* Parameters fd: the FileDescriptor for the file you want to play
* offset: the offset into the file where the data to be played
* starts, in bytes length: the length in bytes of the data to be
* played
*/
RandomAudioPlayer.setDataSource(descriptor.getFileDescriptor(),
descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
RandomAudioPlayer.prepare();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
RandomAudioPlayer.start();
Log.d("In OnClickMethod TagLog", "Start mp");
}
}