2017-11-05 6 views
0

webserviceから入力ストリームを取得してバイト配列に変換するので、一時ファイルを作成してMediaPlayerを使用して再生できます。 mp3)。問題は、私はwhatsappで曲を共有したいと思うが、私はいつでも私が試してみると "失敗した"というメッセージが出る。WhatsAppの共有曲は、常に「失敗しました」というメッセージで終了します。

これは私が取得する方法で、曲再生する:

if (response.body() != null) { 
    byte[] bytes = new byte[0]; 
    try { 
     bytes = toByteArray(response.body().byteStream()); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

mediaPlayer.reset(); 
try { 
    File tempMp3 = File.createTempFile("tempfile", "mp3", getContext().getCacheDir()); 
    tempMp3.deleteOnExit(); 
    FileOutputStream fos = new FileOutputStream(tempMp3); 
    fos.write(mp3); 
    fos.close(); 

    FileInputStream fis = new FileInputStream(tempMp3); 

    mediaPlayer.setDataSource(fis.getFD()); 
    mediaPlayer.prepare(); 
} 
catch (IOException ex) { 
    String s = ex.toString(); 
    ex.printStackTrace(); 
} 

mediaPlayer.start(); 

をこれといくつかの類似の方法は、私はそれを共有しようとしている方法です。

String sharePath = Environment.getExternalStorageDirectory().getPath() 
        + "/tempfile.mp3"; 
      Uri uri = Uri.parse(sharePath); 
      Intent share = new Intent(Intent.ACTION_SEND); 
      share.setType("audio/*"); 
      share.putExtra(Intent.EXTRA_STREAM, uri); 
      startActivity(Intent.createChooser(share, "Share Sound File")); 

歌がうまく再生されていると私は外部記憶装置の読み込みと書き込みの両方の許可を持っていますが、私はバイトやファイルとして、あるいは何らかの作品として、曲を共有するのに助けが必要です。

答えて

0

あなたは、あなたが主な問題はどこにファイルを格納したことだった。この

String sharePath = tempMp3.getAbsolutePath(); 
     Uri uri = Uri.parse(sharePath); 
     Intent share = new Intent(Intent.ACTION_SEND); 
     share.setType("audio/*"); 
     share.putExtra(Intent.EXTRA_STREAM, uri); 
     startActivity(Intent.createChooser(share, getString(R.string.share_song_file))); 

のようにそれを共有することができ

File tempMp3 = new File(Environment.getExternalStorageDirectory() + "/"+ getString(R.string.temp_file) + getString(R.string.dot_mp3)); //<- this is "tempfile" and ".mp3" 

File tempMp3 = File.createTempFile("tempfile", "mp3", getContext().getCacheDir()); 

から変更する必要がありますgetCacheDir()メソッドが使用されているため、他のアプリケーションと共有することはできませんでした。データをファイルに永続的に格納するのではなく、キャッシュファイルを作成するためのもので、アプリケーションのプライベートなものです(createTempFile()はファイル名の末尾に乱数を生成するため、それ)。
また、このソリューションでは、含まれているアクセス許可(外部ストレージへのアクセス)を利用します。

関連する問題