2015-10-16 53 views
1

Im建立mediaplayer的作業和使用Xamarin IDE。 Xamarin中的MainActivity文件有extern .cs。這意味着C#文件,我遇到了一些麻煩。 我需要從SD卡獲取數據。但是當我實現這一點時,我有例外「SetDataSource失敗」。 幫幫我。從Xamarin IDE的SD卡讀取.mp3文件

namespace PlayMusic 
{ 
[Activity (Label = "PlayMusic", MainLauncher = true, Icon = "@drawable/icon")] 
public class MainActivity : Activity 
{ 

    protected override void OnCreate (Bundle bundle) 
    { 
     base.OnCreate (bundle); 

     // Set our view from the "main" layout resource 
     SetContentView (Resource.Layout.Main); 

     // Get our button from the layout resource, 
     // and attach an event to it 

     Button play      = FindViewById<Button> (Resource.Id.play_btn); 

     //MediaPlayer mp    = MediaPlayer.Create (this, Resource.Raw.anniver); 
     MediaPlayer mp     = new MediaPlayer(); 
     var directory     = Android.OS.Environment.ExternalStorageDirectory; 
     var fullFileName    = Path.Combine(directory.ToString(), "anniver.mp3"); 
     mp.SetDataSource (fullFileName); 

     play.Click      += delegate { 
      try{ 
       mp.Start(); 
      } 
      catch(Exception e) 
      { 
       e.StackTrace.ToString(); 
      } 
     }; 
    } 
} 
} 

結果fullFileName = 「/storage/sdcard0/anniver.mp3」 但是當IED去的setDataSource(..)語句,有異常IOException異常,而失敗的setDataSource。 我檢查了anniver.mp3。那麼好。

+0

有人幫助我:'( –

回答

0

嘗試添加Android path separator到您的MP3串路徑:由於您使用的Xamarin你可以使用c#Path.Combine到你的文件,像這樣

string stringPath = Android.OS.Environment.ExternalStorageDirectory.Path; 
mp.SetDataSource (stringPath + Java.IO.File.Separator + "1.mp3"); 
+0

當我調試我的應用程序,stringPath + Java.IO.File.Separator +「1.mp3」=「/storage/sdcard0/1.mp3」 和錯誤SetDataSource失敗 我的SD卡名稱SD卡。我可以對軟件有影響嗎? –

+0

使用adb驗證您的文件位置:http://stackoverflow.com/questions/16796432/how-to-list-all-the-files-in-android-phone-by-using-adb-shell – SushiHangover

1

var directory = Android.OS.Environment.ExternalStorageDirectory; 

var fullFileName = Path.Combine(directory.ToString(), "1.mp3"); 
if (File.Exists(fullFileName)) 
{ 
    //proceed 
} 
+0

我不知道原因,但我不叫道路類... –

+0

你有包括使用System.IO; – CDrosos

+0

結果fullFileName =「/storage/sdcard0/anniver.mp3」 異常:mp.SetData失敗。 我不知道這個代碼中的錯誤在哪裏 –