在uwp中使用WaveFileReader(NAudio)访问文件路径被拒绝



尝试使用以下方法将音频文件合并为一个文件:

byte[] buffer = new byte[1024];
WaveFileWriter waveFileWriter = null;
try
{
foreach (string sourceFile in sourceFiles)
{
WaveFileReader reader=null;

using ( reader = new WaveFileReader(sourceFile))
{
if (waveFileWriter == null)
{
// first time in create new Writer
waveFileWriter = new WaveFileWriter(outputFile, reader.WaveFormat);
}
else
{
if (!reader.WaveFormat.Equals(waveFileWriter.WaveFormat))
{
throw new InvalidOperationException("Can't concatenate WAV Files that don't share the same format");
}
}
int read;
while ((read = reader.Read(buffer, 0, buffer.Length)) > 0)
{
waveFileWriter.WriteData(buffer, 0, read);
}
}
}
}
finally
{
if (waveFileWriter != null)
{
waveFileWriter.Dispose();
}
}
  • outputFile:组合文件的名称
  • sourceFiles:音频文件路径的字符串列表

当使用该方法时,我得到以下异常:

系统。未授权访问异常:";拒绝访问路径"C:\Users\User\Documents\Gebura battle_541f3d9f-a4b9-4491-b6b6-75ede45e1748.wav">

我尝试以管理员身份运行visualstudio,但没有成功。我该怎么做,让它发挥作用?

我检查了WaveFileReader的源代码,它使用File.OpenRead方法通过路径打开文件。不允许在UWP应用程序中使用带有Path的IO/File API,因为UWP应用在沙盒中是隔离的。这就是这种行为的原因。如果你想在UWP应用程序中使用这个API,你可能需要联系NAudio的作者并更改WaveFileReader的源代码。

如果有人遇到同样的问题,我已经找到了解决方案首先,由于某些原因,UWP允许您仅在设置的目录中创建文件(ApplicationData.Current包含允许的文件夹(。您也可以读取和编辑文件,但只能在KnownFolders文件夹或ApplicatioData中。当前的。因此,如果您需要创建一个文件,请在这些文件夹中执行操作,并使用StorageFile移动它们。MoveAsync(StorageFolder destinationFolderPath(;由于某些原因,您可以将文件从这些文件夹移动到其他文件夹移动某些文件的示例:

try
{
StorageFile WhereTo = await KnownFolders.DocumentsLibrary.GetFileAsync("SavingFolderAudioCutter.txt"); // this file contains a path to a folder
string oof = await Windows.Storage.FileIO.ReadTextAsync(WhereTo); //getting a path
StorageFolder dest = await StorageFolder.GetFolderFromPathAsync(oof); //setting StorageFolder path from a string 
string path = ApplicationData.Current.TemporaryFolder.Path + $@"{uniqueName}.wav"; // setting a name for a moved file
StorageFile FromWhere = await StorageFile.GetFileFromPathAsync(path); // Original file location

await FromWhere.MoveAsync(dest);

UtilityFunctions.DeleteFilesFromDir(ApplicationData.Current.TemporaryFolder.Path); // Deleting files from a temporary folder
FileList.Items.Clear();
}
catch
{
MessageDialog dialog = new MessageDialog("The folder is read-only or incorrect choosen path");
await dialog.ShowAsync();
}

最新更新