Android, How to play WAV file programmatically

做~自己de王妃 提交于 2019-12-01 16:21:08

问题


I already have a .wav file in my directory. at the same time i need to play it together with a mp3 file. I used,

String recordedFile = "/storage/sdcard0/PINOYKARAOKE/1373597371359.wav";

MediaPlayer recordedSong = new MediaPlayer();
try{
recordedSong = MediaPlayer.create(ctx, Uri.fromFile(recordedFile));
recordedSong.prepare();
recordedSong.start();
}
catch(Exception e){
}

error: creation failed and it throws IOException


回答1:


Try to create raw folder and put your file there, use this

public void number(int num, Context ctx) {
                 AssetManager am;
        try {
            am = ctx.getAssets();
            AssetFileDescriptor afd = am.openFd("android.resource://"+getPackageName+"/"+R.raw.your_file_name);
            player = new MediaPlayer();
            player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
                    afd.getLength());
            player.prepare();
            player.start();
            player.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    mp.release();
                }

            });
            player.setLooping(false);
                    } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }



回答2:


I've tried @aangwi answer but got FileNodeFoundException

final AssetFileDescriptor afd = myactivity.getResources().openRawResourceFd(R.raw.your_file);
final FileDescriptor fileDescriptor = afd.getFileDescriptor();
MediaPlayer player = new MediaPlayer();
try {
    player.setDataSource(fileDescriptor, afd.getStartOffset(),
    afd.getLength());
    player.setLooping(false);
    player.prepare();
    player.start();
} catch (IOException ex) {
    LOGGER.error(ex.getLocalizedMessage(), ex);
}


来源:https://stackoverflow.com/questions/17606873/android-how-to-play-wav-file-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!