问题描述
let Data = Array(UnsafeMutableRawBufferPointer(start:buffer.mData,count: Int(buffer.mDataByteSize))
问题是:如何将这个指针数组保存到txt文件中?因此,如何将样本值提取到txt文件中。我对Swift没什么经验,我更喜欢C ++
解决方法
....您的缓冲区.....
canActivate(
next: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.service.isLoggedIn;
}
这应该在您的downloadsDirectory中创建文件“ yourFile”
请让我知道。
,您已经具有创建UnsafeMutableRawBufferPointer的代码。使用它来创建数据,并将其写入磁盘:
let buffer = UnsafeRawBufferPointer(start:buffer.mData,count: Int(buffer.mDataByteSize)
let data = Data.withUnsafeBytes(buffer)
let fileURL = //the path to which you want to save
data.write(to: fileURL,options: []
,
我通过避免使用指针数组的特殊情况解决了这个问题。如果其他人想将音频样本写入文本文件,这就是我通过 AVAudioFile 解决问题的方式:
if FileManager.default.fileExists(atPath: getFileURL().path)
{
do{
//Load Audio into Buffer and then write it down to a .txt
let file = try AVAudioFile(forReading: getFileURL())
let format = AVAudioFormat(commonFormat: .pcmFormatFloat32,sampleRate: file.fileFormat.sampleRate,channels: file.fileFormat.channelCount,interleaved: false)
guard let buf = AVAudioPCMBuffer(pcmFormat: format!,frameCapacity: AVAudioFrameCount(file.length)) else{
throw NSError()
}
try file.read(into: buf)
guard buf.floatChannelData != nil else{print("Channel Buffer was not able to be created")
throw NSError()}
let arraySize = Int(buf.frameLength)
print(arraySize,"Samples saved")
let samples = Array(UnsafeBufferPointer(start:buf.floatChannelData![0],count:arraySize))
//Array is going to be encoded and safe
let encoded = try! JSONEncoder().encode(samples)
try encoded.write(to: outputURL())
print("Textfile created.\n")
}catch {print(error)}
}else {print("AudioFile is missing")}