好的,我现在已经有这个问题差不多一个月了。某些音频文件无法播放。它只返回如下错误:
无法初始化该类型的实例' AVFoundation.AVAudioPlayer':本机' initWithContentsOfURL:错误:'方法返回nil。
这里是初始化AudioPlayer的代码:
NSData data = new NSData();
if (AppSession.IsConnected ()) {/*Just a checker if connection is available or not*/
if (uri != null && uri.ToString().Length > 0) {
data = await LoadData (uri);
}
} else { data = null; }
string saveFile = FolderPath(uri, "playthrough");
data.Save(saveFile, false);
NSUrl fileUrl = NSUrl.FromString(saveFile);
audioplayer = AVAudioPlayer.FromUrl(fileUrl);
audioplayer.NumberOfLoops = 0;
audioplayer.Volume = 1.5f;
audioplayer.PrepareToPlay();
audioplayer.Play();
对于LoadData:
public static async Task<NSData> LoadData (NSUrl url)
{
NSData data = new NSData ();
if (url.ToString ().Contains ("http")) {
var httpClient = new HttpClient ();
Task<byte[]> contentsTask = httpClient.GetByteArrayAsync (url.ToString ());
var contents = await contentsTask;
data = NSData.FromArray(contents);
} else { data = NSData.FromUrl (url); }
return data;
}
对于FolderPath:
public static string FolderPath(NSUrl url, string fileName)
{
string[] dotSplitter = url.ToString ().Split (new char[]{ '.' }, 4);
string ext = "";
if (dotSplitter.Length == 4) {
switch (dotSplitter [3]) {
case "wav": ext = ".wav"; break;
case "mp3": ext = ".mp3"; break;
case "3gpp": ext = ".3gpp"; break;
case "mp4": ext = ".mp4"; break;
}
} else {
switch (dotSplitter [0]) {
case "wav": ext = ".wav"; break;
case "mp3": ext = ".mp3"; break;
case "3gpp": ext = ".3gpp"; break;
case "mp4": ext = ".mp4"; break;
}
}
return Path.Combine(TMPDir(), fileName + ext);
}
以下是我用来测试音频的文件:
所以,是的。我为此完成了数十项研究,谷歌,实验和眼泪,但最终我没有任何结果。对此有何解决方案?
答案 0 :(得分:2)
你应该得到的完整例外是:
System.Exception:无法初始化类型的实例&#39; MonoTouch.AVFoundation.AVAudioPlayer&#39;:本机&#39; initWithContentsOfURL:错误:&#39;方法返回零。 通过将MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure设置为false,可以忽略此条件。
按照上面的建议(使用重载接受NSError
)和异常消息中的那个,你得到类似的东西:
MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure = false;
NSError error;
using (var url = NSUrl.FromString ("http://files.parsetfss.com/6ea4a3c5-a4e2-463f-8374-247d5db0fbd5/tfss-c7db3001-b7b0-465d-b59b-233c1fe568ec-filtered_427201531308PM_song.wav"))
using (var player = AVAudioPlayer.FromUrl (url, out error)) {
Console.WriteLine (error);
}
你会得到:
无法完成操作。 (OSStatus错误2003334207。)
这是AVAudioPlayer
的常见错误。如果您使用NSData
(本地文件),我也会收到相同的错误。但是AVPlayer
加载网址就好......