下面的录音机只在第一次工作,如果你尝试第二次录音,它会在尝试 AudioFileWritePackets 时给出错误“kAudioFileInvalidPacketOffsetError”。
知道为什么会这样吗?
提前致谢
记录器
import UIKit
import CoreAudio
import AudioToolbox
class SpeechRecorder: NSObject {
static let sharedInstance = SpeechRecorder()
// MARK:- properties
@objc enum Status: Int {
case ready
case busy
case error
}
internal struct RecordState {
var format: AudioStreamBasicDescription
var queue: UnsafeMutablePointer<AudioQueueRef?>
var buffers: [AudioQueueBufferRef?]
var file: AudioFileID?
var currentPacket: Int64
var recording: Bool
};
private var recordState: RecordState?
var format: AudioFormatID {
get { return recordState!.format.mFormatID }
set { recordState!.format.mFormatID = newValue }
}
var sampleRate: Float64 {
get { return recordState!.format.mSampleRate }
set { recordState!.format.mSampleRate = newValue }
}
var formatFlags: AudioFormatFlags {
get { return recordState!.format.mFormatFlags }
set { recordState!.format.mFormatFlags = newValue }
}
var channelsPerFrame: UInt32 {
get { return recordState!.format.mChannelsPerFrame }
set { recordState!.format.mChannelsPerFrame = newValue }
}
var bitsPerChannel: UInt32 {
get { return recordState!.format.mBitsPerChannel }
set { recordState!.format.mBitsPerChannel = newValue }
}
var framesPerPacket: UInt32 {
get { return recordState!.format.mFramesPerPacket }
set { recordState!.format.mFramesPerPacket = newValue }
}
var bytesPerFrame: UInt32 {
get { return recordState!.format.mBytesPerFrame }
set { recordState!.format.mBytesPerFrame = newValue }
}
var bytesPerPacket: UInt32 {
get { return recordState!.format.mBytesPerPacket }
set { recordState!.format.mBytesPerPacket = newValue }
}
//MARK: - Handlers
public var handler: ((Status) -> Void)?
// MARK:- Init
override init()
{
super.init()
self.recordState = RecordState(format: AudioStreamBasicDescription(),
queue: UnsafeMutablePointer<AudioQueueRef?>.allocate(capacity: 1),
buffers: [AudioQueueBufferRef?](repeating: nil, count: 1),
file: nil,
currentPacket: 0,
recording: false)
}//eom
// MARK:- OutputFile
func setOutputFile(path: String)
{
setOutputFile(url: URL(fileURLWithPath: path))
}
func setOutputFile(url: URL)
{
AudioFileCreateWithURL(url as CFURL,
kAudioFileWAVEType,
&recordState!.format,
AudioFileFlags.dontPageAlignAudioData.union(.eraseFile),
&recordState!.file)
}
// MARK:- Start / Stop Recording
func start()
{
handler?(.busy)
let inputAudioQueue: AudioQueueInputCallback =
{ (userData: UnsafeMutableRawPointer?,
audioQueue: AudioQueueRef,
bufferQueue: AudioQueueBufferRef,
startTime: UnsafePointer<AudioTimeStamp>,
packets: UInt32,
packetDescription: UnsafePointer<AudioStreamPacketDescription>?) in
let internalRSP = unsafeBitCast(userData, to: UnsafeMutablePointer<RecordState>.self)
if packets > 0
{
var packetsReceived = packets
let outputStream:OSStatus = AudioFileWritePackets(internalRSP.pointee.file!,
false,
bufferQueue.pointee.mAudioDataByteSize,
packetDescription,
internalRSP.pointee.currentPacket,
&packetsReceived,
bufferQueue.pointee.mAudioData)
if outputStream != 0
{
// This is where the error occurs when recording after the first time
//<----DEBUG
switch outputStream
{
case kAudioFilePermissionsError:
print("kAudioFilePermissionsError")
break
case kAudioFileNotOptimizedError:
print("kAudioFileNotOptimizedError")
break
case kAudioFileInvalidChunkError:
print("kAudioFileInvalidChunkError")
break
case kAudioFileDoesNotAllow64BitDataSizeError:
print("kAudioFileDoesNotAllow64BitDataSizeError")
break
case kAudioFileInvalidPacketOffsetError:
print("kAudioFileInvalidPacketOffsetError")
break
case kAudioFileInvalidFileError:
print("kAudioFileInvalidFileError")
break
case kAudioFileOperationNotSupportedError:
print("kAudioFileOperationNotSupportedError")
break
case kAudioFileNotOpenError:
print("kAudioFileNotOpenError")
break
case kAudioFileEndOfFileError:
print("kAudioFileEndOfFileError")
break
case kAudioFilePositionError:
print("kAudioFilePositionError")
break
case kAudioFileFileNotFoundError:
print("kAudioFileFileNotFoundError")
break
case kAudioFileUnspecifiedError:
print("kAudioFileUnspecifiedError")
break
case kAudioFileUnsupportedFileTypeError:
print("kAudioFileUnsupportedFileTypeError")
break
case kAudioFileUnsupportedDataFormatError:
print("kAudioFileUnsupportedDataFormatError")
break
case kAudioFileUnsupportedPropertyError:
print("kAudioFileUnsupportedPropertyError")
break
case kAudioFileBadPropertySizeError:
print("kAudioFileBadPropertySizeError")
break
default:
print("unknown error")
break
}
//<----DEBUG
}
internalRSP.pointee.currentPacket += Int64(packetsReceived)
}
if internalRSP.pointee.recording
{
let outputStream:OSStatus = AudioQueueEnqueueBuffer(audioQueue, bufferQueue, 0, nil)
if outputStream != 0
{
// This is where the error occurs when recording after the first time
//<----DEBUG
switch outputStream
{
case kAudioFilePermissionsError:
print("kAudioFilePermissionsError")
break
case kAudioFileNotOptimizedError:
print("kAudioFileNotOptimizedError")
break
case kAudioFileInvalidChunkError:
print("kAudioFileInvalidChunkError")
break
case kAudioFileDoesNotAllow64BitDataSizeError:
print("kAudioFileDoesNotAllow64BitDataSizeError")
break
case kAudioFileInvalidPacketOffsetError:
print("kAudioFileInvalidPacketOffsetError")
break
case kAudioFileInvalidFileError:
print("kAudioFileInvalidFileError")
break
case kAudioFileOperationNotSupportedError:
print("kAudioFileOperationNotSupportedError")
break
case kAudioFileNotOpenError:
print("kAudioFileNotOpenError")
break
case kAudioFileEndOfFileError:
print("kAudioFileEndOfFileError")
break
case kAudioFilePositionError:
print("kAudioFilePositionError")
break
case kAudioFileFileNotFoundError:
print("kAudioFileFileNotFoundError")
break
case kAudioFileUnspecifiedError:
print("kAudioFileUnspecifiedError")
break
case kAudioFileUnsupportedFileTypeError:
print("kAudioFileUnsupportedFileTypeError")
break
case kAudioFileUnsupportedDataFormatError:
print("kAudioFileUnsupportedDataFormatError")
break
case kAudioFileUnsupportedPropertyError:
print("kAudioFileUnsupportedPropertyError")
break
case kAudioFileBadPropertySizeError:
print("kAudioFileBadPropertySizeError")
break
default:
print("unknown error")
break
}
//<----DEBUG
}
}
}
let queueResults = AudioQueueNewInput(&recordState!.format, inputAudioQueue, &recordState, nil, nil, 0, recordState!.queue)
if queueResults == 0
{
let bufferByteSize: Int = calculate(format: recordState!.format, seconds: 0.5)
for index in (0..<recordState!.buffers.count)
{
AudioQueueAllocateBuffer(recordState!.queue.pointee!, UInt32(bufferByteSize), &recordState!.buffers[index])
AudioQueueEnqueueBuffer(recordState!.queue.pointee!, recordState!.buffers[index]!, 0, nil)
}
AudioQueueStart(recordState!.queue.pointee!, nil)
recordState?.recording = true
}
else
{
print("Error setting audio input.")
handler?(.error)
}
}//eom
func stop()
{
recordState?.recording = false
if let recordingState: RecordState = recordState
{
AudioQueueStop(recordingState.queue.pointee!, true)
AudioQueueDispose(recordingState.queue.pointee!, true)
AudioFileClose(recordingState.file!)
handler?(.ready)
}
}//eom
// MARK:- Helper methods
func calculate(format: AudioStreamBasicDescription, seconds: Double) -> Int
{
let framesRequiredForBufferTime = Int(ceil(seconds * format.mSampleRate))
if framesRequiredForBufferTime > 0
{
return (framesRequiredForBufferTime * Int(format.mBytesPerFrame))
}
else
{
var maximumPacketSize = UInt32(0)
if format.mBytesPerPacket > 0
{
maximumPacketSize = format.mBytesPerPacket
}
else
{
audioQueueProperty(propertyId: kAudioQueueProperty_MaximumOutputPacketSize, value: &maximumPacketSize)
}
var packets = 0
if format.mFramesPerPacket > 0
{
packets = (framesRequiredForBufferTime / Int(format.mFramesPerPacket))
} else
{
packets = framesRequiredForBufferTime
}
if packets == 0
{
packets = 1
}
return (packets * Int(maximumPacketSize))
}
}//eom
func audioQueueProperty<T>(propertyId: AudioQueuePropertyID, value: inout T)
{
let propertySize = UnsafeMutablePointer<UInt32>.allocate(capacity: 1)
propertySize.pointee = UInt32(MemoryLayout<T>.size)
let queueResults = AudioQueueGetProperty(recordState!.queue.pointee!, propertyId, &value, propertySize)
propertySize.deallocate(capacity: 1)
if queueResults != 0 {
print("Unable to get audio queue property.")
}
}//eom
}
View Controller
import UIKit
import AudioToolbox
class ViewController: UIViewController {
//MARK: - Properties
var recorder:SpeechRecorder?
@IBOutlet weak var startStopRecordingButton: UIButton!
//MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
//having same recorder gives error
recorder = SpeechRecorder()
}
//MARK: - Start / End Recording
func startRecording()
{
//alloc/init recorder everytime we start recording gives no error
//recorder = SpeechRecorder()
//settings
recorder?.format = kAudioFormatLinearPCM
recorder?.sampleRate = 16000;
recorder?.channelsPerFrame = 1
recorder?.bitsPerChannel = 16
recorder?.framesPerPacket = 1
recorder?.bytesPerFrame = ((recorder!.channelsPerFrame * recorder!.bitsPerChannel) / 8)
recorder?.bytesPerPacket = recorder!.bytesPerFrame * recorder!.framesPerPacket
recorder?.formatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked
//outputfile
let outputfilePath:String = MyFileManager().createTempFilePathWithUniqueName("recorderAudio", andExtension: "wav")
print("temp filepath: ", outputfilePath)
recorder?.setOutputFile(path: outputfilePath)
//handler
recorder?.handler = { [weak self] status in
switch status
{
case .busy:
print("started Recording\n\n")
break
case .ready:
print("finish recorder, ready to start recording\n\n")
break
case .error:
print("error occur with recorder\n\n")
DispatchQueue.main.async
{
self?.startStopRecordingButton.isSelected = false
self?.view.backgroundColor = UIColor.white
}
break
}
}//
recorder?.start()
}//eom
func stopRecording()
{
recorder?.stop()
}//eom
//MARK: - Actions
@IBAction func startStopRecording()
{
if startStopRecordingButton.isSelected
{
startStopRecordingButton.isSelected = false
self.view.backgroundColor = UIColor.white
startStopRecordingButton.setTitle("Start Recording", for: UIControlState.normal)
self.stopRecording()
}
else
{
startStopRecordingButton.isSelected = true
self.view.backgroundColor = UIColor.green
startStopRecordingButton.setTitle("Stop Recording", for: UIControlState.normal)
self.startRecording()
}
}//eom
//MARK: - Memory
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
FileManager(创建临时文件路径)
import Foundation
@objc class MyFileManager:NSObject
{
private let unique_debug = true
private var _temporyDirectory:String = ""
//MARK: - Properties
var directory:String {
return _temporyDirectory
}
//MARK: - Init
override init() {
super.init()
_temporyDirectory = NSTemporaryDirectory()
}//eom
func createHomeDirFileUniqueWithName(_ myFileName:String, andExtension fileExtension:String)->URL
{
//filename
let time:Date = Date.init()
let dateformatter:DateFormatter = DateFormatter()
dateformatter .dateFormat = "ddMMyyyy-hh-mm-ss-a"
let tempDate:String = dateformatter .string(from: time)
let tempFileName = "\(myFileName)-\(tempDate).\(fileExtension)"
//directory
var documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
documentsDirectory.appendPathComponent(tempFileName)
if unique_debug { print("\(documentsDirectory)") }
return documentsDirectory
}//eom
//MARK: - Names
func createGlobalUniqueFileName(_ myFileName:String)->String
{
let guid = ProcessInfo.processInfo.globallyUniqueString
let uniqueFileName = ("\(myFileName)_\(guid)")
if unique_debug { print("\(uniqueFileName)") }
return uniqueFileName
}//eom
func createUniqueNameWithFilename(_ myFileName:String, andExtension fileExtension:String)->String
{
//filename
let time:Date = Date.init()
let dateformatter:DateFormatter = DateFormatter()
dateformatter .dateFormat = "ddMMyyyy-hh-mm-ss-a"
let currentDateString = dateformatter .string(from: time)
let finalName = myFileName + currentDateString + "." + fileExtension
if unique_debug { print("\(finalName)") }
return finalName
}//eom
//MARK: - Paths
func createTempFilePathWithUniqueName(_ myFileName:String, andExtension fileExtension:String)->String
{
let tempFileName = self.createUniqueNameWithFilename(myFileName, andExtension: fileExtension)
let tempFile = _temporyDirectory + tempFileName
if unique_debug { print("\(tempFile)") }
return tempFile
}//eom
//MARK: - Helpers
func enumerateDirectory(directory:String)
{
do
{
let filesInDir:[String] = try FileManager.default.contentsOfDirectory(atPath: directory)
for currFile in filesInDir {
print(currFile)
}//eofl
}
catch let error
{
print("error: \(error.localizedDescription)")
}
}//eom
func doesFileExistInDirectory(filename:String) -> Bool {
do
{
let filesInDir:[String] = try FileManager.default.contentsOfDirectory(atPath: _temporyDirectory)
for currFile in filesInDir
{
print(currFile)
if currFile == filename {
return true
}
}//eofl
}
catch let error
{
print("error: \(error.localizedDescription)")
}
return false
}//eom
}//eoc
最佳答案
您没有将 currentPacket 计数重置为零,因此在后续录音中,您要求 AudioFileWritePackets 从非零起始数据包开始写入其新文件,它拒绝这样做。
正确的解决方案(可能)是在每次开始录制时重新创建 RecordState,尽管设置不当
recordState!.currentPacket = 0
在调用 AudioQueueNewInput 之前似乎也有效。
关于ios - Swift 3 LPCM 录音机 |错误 : kAudioFileInvalidPacketOffsetError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40558374/
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的
1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里
print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上
当我将IO::popen与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:irb>IO.popen"fakefake"#=>#irb>(irb):1:commandnotfound:fakefake有什么方法可以捕获此错误,以便我可以在脚本中进行检查? 最佳答案 是:升级到ruby1.9。如果您在1.9中运行它,则会引发Errno::ENOENT,您将能够拯救它。(编辑)这是在1.8中的一种hackish方式:error=IO.pipe$stderr.reopenerror[1]pipe=IO.popen'qwe'#
当我尝试使用“套接字”库中的方法“read_nonblock”时出现以下错误IO::EAGAINWaitReadable:Resourcetemporarilyunavailable-readwouldblock但是当我通过终端上的IRB尝试时它工作正常如何让它读取缓冲区? 最佳答案 IgetthefollowingerrorwhenItrytousethemethod"read_nonblock"fromthe"socket"library当缓冲区中的数据未准备好时,这是预期的行为。由于异常IO::EAGAINWaitReadab
我需要将目录中的一堆文件上传到S3。由于上传所需的90%以上的时间都花在了等待http请求完成上,所以我想以某种方式同时执行其中的几个。Fibers能帮我解决这个问题吗?它们被描述为解决此类问题的一种方法,但我想不出在http调用阻塞时我可以做任何工作的任何方法。有什么方法可以在没有线程的情况下解决这个问题? 最佳答案 我没有使用1.9中的纤程,但是1.8.6中的常规线程可以解决这个问题。尝试使用队列http://ruby-doc.org/stdlib/libdoc/thread/rdoc/classes/Queue.html查看文
在ruby中...我有一个由外部进程创建的IO对象,我需要从中获取文件名。然而我似乎只能得到文件描述符(3),这对我来说不是很有用。有没有办法从此对象获取文件名甚至获取文件对象?我正在从通知程序中获取IO对象。所以这也可能是获取文件路径的一种方式? 最佳答案 关于howtogetathefilenameinC也有类似的问题,我将在这里以ruby的方式给出这个问题的答案。在Linux中获取文件名假设io是您的IO对象。以下代码为您提供了文件名。File.readlink("/proc/self/fd/#{io.fileno}")例
文章目录前言核心逻辑配置iSH安装Python创建Python脚本配置启动文件测试效果快捷指令前言iOS快捷指令所能做的操作极为有限。假如快捷指令能运行Python程序,那么可操作空间就瞬间变大了。iSH是一款免费的iOS软件,它模拟了一个类似Linux的命令行解释器。我们将在iSH中运行Python程序,然后在快捷指令中获取Python程序的输出。核心逻辑我们用一个“获取当前日期”的Python程序作为演示(其实快捷指令中本身存在“获取当前日期”的操作,因而此需求可以不用Python,这里仅仅为了演示方便),核心代码如下。>>>importtime>>>time.strftime('%Y-%
iOS适配Unity-2019背景由于2019起,Unity的Xcode工程,更改了项目结构。Unity2018的结构:可以看Targets只有一个Unity-iPhone,Unity-iPhone直接依赖管理三方库。Unity2019以后:Targets多了一个UnityFramework,UnityFramework管理三方库,Unity-iPhone依赖于UnityFramwork。所以升级后,会有若干的问题,以下是对问题的解决方式。问题一错误描述error:exportArchive:Missingsigningidentifierat"/var/folders/fr//T/Xcode