Как вы играете в Android InputStream на MediaPlayer? - PullRequest
15 голосов
/ 21 апреля 2011

Итак, у меня есть небольшой аудиофайл в папке с активами, и я хотел открыть InputStream для записи в буфер, затем записать во временный файл, затем я открыл MediaPlayer для воспроизведения этого временного файла. Проблема в том, что когда медиаплеер нажимает mp.Prepare (), он не воспроизводится и никогда не достигает тоста. Кто-нибудь когда-нибудь делал это раньше?

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    InputStream str;

    try {

        str = this.getAssets().open("onestop.mid");
        Toast.makeText(this, "Successful Input Stream Opened.", Toast.LENGTH_SHORT).show();
        takeInputStream(str);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}//end on create

public void takeInputStream(InputStream stream) throws IOException
{
    //fileBeingBuffered = (FileInputStream) stream;
    //Toast.makeText(this, "sucessful stream conversion.", Toast.LENGTH_SHORT).show();
    try
    {
        convertedFile = File.createTempFile("convertedFile", ".dat", getDir("filez", 0));
        Toast.makeText(this, "Successful file and folder creation.", Toast.LENGTH_SHORT).show();

        out = new FileOutputStream(convertedFile);
        Toast.makeText(this, "Success out set as output stream.", Toast.LENGTH_SHORT).show();

        //RIGHT AROUND HERE -----------

        byte buffer[] = new byte[16384];
        int length = 0;
        while ( (length = stream.read(buffer)) != -1 ) 
        {
          out.write(buffer,0, length);
        }

        //stream.read(buffer);
        Toast.makeText(this, "Success buffer is filled.", Toast.LENGTH_SHORT).show();
        out.close();

        playFile();
    }catch(Exception e)
    {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }//end catch
}//end grabBuffer

public void playFile()
{
    try {
        String path = convertedFile.getAbsolutePath();
        mp = new MediaPlayer();
        mp.setDataSource(path);
        Toast.makeText(this, "Success, Path has been set", Toast.LENGTH_SHORT).show();

        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mp.prepare();
        Toast.makeText(this, "Media Player prepared", Toast.LENGTH_SHORT).show();

        mp.start();
        Toast.makeText(this, "Media Player playing", Toast.LENGTH_SHORT).show();
    } catch (IllegalArgumentException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    } catch (IllegalStateException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }

}//end playFile

Ответы [ 2 ]

14 голосов
/ 22 апреля 2011

Исправлено.Оказывается, что после записи буфера во временный файл, созданный «File», вы можете открыть этот файл с помощью FileInputStream, а затем продолжить воспроизведение, как показано ниже.Спасибо за вашу помощь, ребята.

mp = new MediaPlayer();

FileInputStream fis = new FileInputStream(convertedFile);
mp.setDataSource(fis.getFD());

Toast.makeText(this, "Success, Path has been set", Toast.LENGTH_SHORT).show();

mp.prepare();
mp.start();
1 голос
/ 24 января 2013

Это код, который работал для меня

//preserved to stop previous actions 
MediaPlayer lastmp;

public void playSound(String file) {
    try {
        if (lastmp!=null) lastmp.stop();
        MediaPlayer mp = new MediaPlayer();
        lastmp = mp;
        AssetFileDescriptor descriptor;

        AssetManager assetManager = act.getAssets();

        descriptor =  assetManager.openFd(fileName);
        mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
        descriptor.close();
        mp.prepare();
        mp.start();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

файл должен находиться в папке активов

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...