Dive into the technical aspects of audio on your device, including codecs, format support, and customization options.

Audio Documentation

Posts under Audio subtopic

Post

Replies

Boosts

Views

Activity

Bluetooth with AVAudioSessionPlaybackAndRecord
Hello!I am working on an app that plays audio and accepts voice commands simultaniously. When I play audio through bluetooth in my car, the Audio Session for the app uses the Bluetooth HFP ports. This causes the output audio quality to become very poor. If I switch to AVAudioSessionPlayback, the output is on the A2DP port, which sounds great. Ideally I would like to be able to play ouput through A2DP, and accept input through HFP, but I assume this is a limitation of bluetooth, or everything would already work this way to improve sound quality. For my app it would be acceptable to accept input from the phone's microphone, and play the audio through bluetooth, but this also seems impossible as described here: http://stackoverflow.com/questions/22146406/ios-input-mic-output-bluetooth-device. Any advice on improving playback audio quality when connected to bluetooth while using AVAudioSessionPlayback and record would be greatly appreciated. Has anyone encounted this issue before and had a suitable fix?Thanks!
3
0
5.0k
Oct ’21
AVAudioRecorder and audio data file offset
I'm trying to get a wav file to outside API from iOS. I've managed to do the file and post it from iPhone but the service doesn't take it (API errors are not helpful either). I've managed to track down the difference between a file I manage to send to the service and the file save with iPhone to audio data file offset parameter. afinfo command gives the working file value 44 and iOS saved audiofile has 4096. Is there any way to change this to 44 also on iOS?My current settings for AVAudioRecorder:let recordSettings = [ AVNumberOfChannelsKey: 1, AVSampleRateKey: 16000.0, AVFormatIDKey: kAudioFormatLinearPCM, AVLinearPCMBitDepthKey: 8, AVLinearPCMIsBigEndianKey: false, AVLinearPCMIsFloatKey: false, AVLinearPCMIsNonInterleaved: false ]
2
0
1.1k
Apr ’23
CMSampleBufferSetDataBufferFromAudioBufferList returning -12731
I am trying to take a video file read it in using AVAssetReader and pass the audio off to CoreAudio for processing (adding effects and stuff) before saving it back out to disk using AVAssetWriter. I would like to point out that if i set the componentSubType on AudioComponentDescription of my output node as RemoteIO, things play correctly though the speakers. This makes me confident that my AUGraph is properly setup as I can hear things working. I am setting the subType to GenericOutput though so I can do the rendering myself and get back the adjusted audio.I am reading in the audio and i pass the CMSampleBufferRef off to copyBuffer. This puts the audio into a circular buffer that will be read in later.- (void)copyBuffer:(CMSampleBufferRef)buf { if (_readyForMoreBytes == NO) { return; } AudioBufferList abl; CMBlockBufferRef blockBuffer; CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(buf, NULL, &abl, sizeof(abl), NULL, NULL, kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment, &blockBuffer); UInt32 size = (unsigned int)CMSampleBufferGetTotalSampleSize(buf); BOOL bytesCopied = TPCircularBufferProduceBytes(&circularBuffer, abl.mBuffers[0].mData, size); if (!bytesCopied){ / _readyForMoreBytes = NO; if (size > kRescueBufferSize){ NSLog(@"Unable to allocate enought space for rescue buffer, dropping audio frame"); } else { if (rescueBuffer == nil) { rescueBuffer = malloc(kRescueBufferSize); } rescueBufferSize = size; memcpy(rescueBuffer, abl.mBuffers[0].mData, size); } } CFRelease(blockBuffer); if (!self.hasBuffer && bytesCopied > 0) { self.hasBuffer = YES; } }Next I call processOutput. This will do a manual reder on the outputUnit. When AudioUnitRender is called it invokes the playbackCallback below, which is what is hooked up as input callback on my first node. playbackCallback pulls the data off the circular buffer and feeds it into the audioBufferList passed in. Like I said before if the output is set as RemoteIO this will cause the audio to correctly be played on the speakers. When AudioUnitRender finishes, it returns noErr and the bufferList object contains valid data. When I call CMSampleBufferSetDataBufferFromAudioBufferList though I get kCMSampleBufferError_RequiredParameterMissing (-12731).-(CMSampleBufferRef)processOutput { if(self.offline == NO) { return NULL; } AudioUnitRenderActionFlags flags = 0; AudioTimeStamp inTimeStamp; memset(&inTimeStamp, 0, sizeof(AudioTimeStamp)); inTimeStamp.mFlags = kAudioTimeStampSampleTimeValid; UInt32 busNumber = 0; UInt32 numberFrames = 512; inTimeStamp.mSampleTime = 0; UInt32 channelCount = 2; AudioBufferList *bufferList = (AudioBufferList*)malloc(sizeof(AudioBufferList)+sizeof(AudioBuffer)*(channelCount-1)); bufferList->mNumberBuffers = channelCount; for (int j=0; j<channelCount; j++) { AudioBuffer buffer = {0}; buffer.mNumberChannels = 1; buffer.mDataByteSize = numberFrames*sizeof(SInt32); buffer.mData = calloc(numberFrames,sizeof(SInt32)); bufferList->mBuffers[j] = buffer; } CheckError(AudioUnitRender(outputUnit, &flags, &inTimeStamp, busNumber, numberFrames, bufferList), @"AudioUnitRender outputUnit"); CMSampleBufferRef sampleBufferRef = NULL; CMFormatDescriptionRef format = NULL; CMSampleTimingInfo timing = { CMTimeMake(1, 44100), kCMTimeZero, kCMTimeInvalid }; AudioStreamBasicDescription audioFormat = self.audioFormat; CheckError(CMAudioFormatDescriptionCreate(kCFAllocatorDefault, &audioFormat, 0, NULL, 0, NULL, NULL, &format), @"CMAudioFormatDescriptionCreate"); CheckError(CMSampleBufferCreate(kCFAllocatorDefault, NULL, false, NULL, NULL, format, numberFrames, 1, &timing, 0, NULL, &sampleBufferRef), @"CMSampleBufferCreate"); CheckError(CMSampleBufferSetDataBufferFromAudioBufferList(sampleBufferRef, kCFAllocatorDefault, kCFAllocatorDefault, 0, bufferList), @"CMSampleBufferSetDataBufferFromAudioBufferList"); return sampleBufferRef; }static OSStatus playbackCallback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { int numberOfChannels = ioData->mBuffers[0].mNumberChannels; SInt16 *outSample = (SInt16 *)ioData->mBuffers[0].mData; / memset(outSample, 0, ioData->mBuffers[0].mDataByteSize); MyAudioPlayer *p = (__bridge MyAudioPlayer *)inRefCon; if (p.hasBuffer){ int32_t availableBytes; SInt16 *bufferTail = TPCircularBufferTail([p getBuffer], &availableBytes); int32_t requestedBytesSize = inNumberFrames * kUnitSize * numberOfChannels; int bytesToRead = MIN(availableBytes, requestedBytesSize); memcpy(outSample, bufferTail, bytesToRead); TPCircularBufferConsume([p getBuffer], bytesToRead); if (availableBytes <= requestedBytesSize*2){ [p setReadyForMoreBytes]; } if (availableBytes <= requestedBytesSize) { p.hasBuffer = NO; } } return noErr; }The CMSampleBufferRef I pass in looks valid (below is a dump of the object from the debugger)CMSampleBuffer 0x7f87d2a03120 retainCount: 1 allocator: 0x103333180 invalid = NO dataReady = NO makeDataReadyCallback = 0x0 makeDataReadyRefcon = 0x0 formatDescription = <CMAudioFormatDescription 0x7f87d2a02b20 [0x103333180]> { mediaType:'soun' mediaSubType:'lpcm' mediaSpecific: { ASBD: { mSampleRate: 44100.000000 mFormatID: 'lpcm' mFormatFlags: 0xc2c mBytesPerPacket: 2 mFramesPerPacket: 1 mBytesPerFrame: 2 mChannelsPerFrame: 1 mBitsPerChannel: 16 } cookie: {(null)} ACL: {(null)} } extensions: {(null)} } sbufToTrackReadiness = 0x0 numSamples = 512 sampleTimingArray[1] = { {PTS = {0/1 = 0.000}, DTS = {INVALID}, duration = {1/44100 = 0.000}}, } dataBuffer = 0x0The buffer list looks like thisPrinting description of bufferList: (AudioBufferList *) bufferList = 0x00007f87d280b0a0 Printing description of bufferList->mNumberBuffers: (UInt32) mNumberBuffers = 2 Printing description of bufferList->mBuffers: (AudioBuffer [1]) mBuffers = { [0] = (mNumberChannels = 1, mDataByteSize = 2048, mData = 0x00007f87d3008c00) }Really at a loss here, hoping someone can help. Thanks,In case it matters i am debuggin this in ios 8.3 simulator and the audio is coming from a mp4 that i shot on my iphone 6 then saved to my laptop.
4
0
6.8k
Aug ’21
Can Audio Unit latency be updated after initialization?
I'm having trouble updating kAudioUnitProperty_Latency in an AU after the plugin has been initialized. Just sending property changed events to the AU host for kAudioUnitProperty_Latency does not seem to do the trick in Logic Pro X, and I can't find a good way to make it reset.I'm aware that a host can't really seamlessly change the latency compensation, but I'm fine with glitches since this is not something that happens a lot (and definitely not possible to automate or anything like that).Is it at all possible? I really want to avoid having a fixed large delay and compensate internally. (Not because of the complexity, but because I don't want to add more latency than needed in the general case.)
3
0
1.3k
Oct ’21
Random AVAudioEngine crash
I am seeing a random crash on the AVAudioEngine startAndReturnError method call. I am not able to reproduce this but I am getting a lot of crash reports from the application on the store. My application mix audio from mulitiple files which I pretty much copy the code from the sample project UsingAVAudioEngineforPlaybackMixingandRecording. I tried to add try-catch block to the call and it does not seem to catch the exception. Any ideas or suggestion on how to debug this? It happens across device models (iPhone, iPad, iPod) and iOS (8 and 9)Thread : Fatal Exception: com.apple.coreaudio.avfaudio0 CoreFoundation 0x23d9468b __exceptionPreprocess1 libobjc.A.dylib 0x35292e17 objc_exception_throw2 CoreFoundation 0x23d94561 +[NSException raise:format:]3 libAVFAudio.dylib 0x22652c21 AVAE_RaiseException(NSString*, ...)4 libAVFAudio.dylib 0x22665dd5 AVAudioEngineGraph::PerformCommand(AUGraphNode&, AVAudioEngineGraph::ENodeCommand, void*, unsigned long) const5 libAVFAudio.dylib 0x226669e3 AVAudioEngineGraph::Initialize()6 libAVFAudio.dylib 0x226a3cc3 AVAudioEngineImpl::Initialize()7 libAVFAudio.dylib 0x226a2bdf AVAudioEngineImpl::Start(NSError**)8 libAVFAudio.dylib 0x226a2b53 -[AVAudioEngine startAndReturnError:]9 Acapella 0x000bd98b __33-[MCAudioMixer initWithMetadata:]_block_invoke (MCAudioMixer.m:182)10 Foundation 0x24b48b39 __22-[__NSObserver _doit:]_block_invoke11 Foundation 0x24b4c80d __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__12 Foundation 0x24aae217 -[NSBlockOperation main]13 Foundation 0x24aa04e1 -[__NSOperationInternal _start:]14 Foundation 0x24b4eac5 __NSOQSchedule_f15 libdispatch.dylib 0x35994d17 _dispatch_client_callout16 libdispatch.dylib 0x359a30b1 _dispatch_main_queue_callback_4CF$VARIANT$mp17 CoreFoundation 0x23d579ad __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__18 CoreFoundation 0x23d55ea7 __CFRunLoopRun19 CoreFoundation 0x23ca9249 CFRunLoopRunSpecific20 CoreFoundation 0x23ca9035 CFRunLoopRunInMode21 GraphicsServices 0x2cd5bad1 GSEventRunModal22 UIKit 0x27ebe8a9 UIApplicationMain23 Acapella 0x0015fc63 main (main.m:14)24 libdyld.dylib 0x359de873 start
7
1
5.7k
Mar ’22
AVCaptureDevice: Camera frame rate off...
It seems the camera produces unexpected results in terms of not quite matching the frame rate given. Specifically, if I set my AVCaptureDevice's activeVideoMaxFrameDuration and activeVideoMinFrameDuration to a CMTimeMake(1,30) I get a frame rate of 30.02 Hz. More curiously, if I set it to CMTimeMake(100,2997), I get a frame rate of 29.02 Hz, so almost an entire Hz or 3% off. At CMTimeMake(1,25) I get 25.01 Hz, and at CMTimeMake(1,24) I get 24.01 Hz. The times are measured by the frames' CMSampleBufferGetPresentationTimeStamp(). So for the round numbers, I'm about 0.1% off and for 29.97 Hz I'm 3% off. 0.1% may not sound like much, but if I want to record at a fixed standard frame rate it means a lost or extra frame every other minute. This happens both on iPhone 6 and on iPhone 6S, and the numbers were obtained in the 1080p 2-60Hz mode. To explore the oddity yet a bit further, at CMTimeMake(100,2999) I get 29.03 Hz and at CMTimeMake(100,3001) I get 30.02 Hz. So it could be that the camera only supports multiples of 1 Hz frame rate intervals, but not exactly.To satisfy my curiousity, I wrote a PLL stabilization around the camera that changes the frame rate depending on whether the video stream is currently ahead or behind where it should be, and that sort of works, but only if cinematic stabilization is off, and that also doesn't feel like the right way to use the built-in camera. Am I missing something? In particular, the result where for the 29.97 specification I'm getting 29 Hz seems really odd, given that this is a very common frame rate. Obviously a phone isn't a true real-time operating system and I don't mind individual frames being off a little bit, but there should be enough regulation around it so as not to cause missed frames if I record for a while.
2
0
1.3k
Apr ’23
Creating a new MIDI control surface mapping driver for Logic Pro X
We need to developpe a new "control surface mapping driver" for Logic Pro X, to match the "simple" fonctionnal requiements of our Tangerine Automation InterfaceI'm trying to find the info on how to create the "mapping driver" that will translate our interface "hardware/midi mapping" to Logic Pro X internal controllers acces. (volume, mutes, automation modes etc...)Ou interface is already reconnized as 5 ports Plug&Play USB midi device. It can be used with the HUI mapping in Logic Pro x but we want to get better control behavior, with our own mapping Any pointer on where to look in the apple developer section would be appriciateddbmdbu
5
0
4.3k
Nov ’21
Using AVAudioEngine to record to compressed file
I'm trying to use AVAudioEngine to record sounds from the microphone together with various sound effect files to a AVAudioFile.I create an AVAudioFile like this:let settings = self.engine.mainMixerNode.outputFormatForBus(0).settingstry self.audioFile = AVAudioFile(forWriting: self.audioURL, settings: settings, commonFormat: .PCMFormatFloat32, interleaved: false)I install a tap on the audio engine's mainMixerNode, where I write the buffer to the file:self.engine.mainMixerNode.installTapOnBus(0, bufferSize: 4096, format: self.engine.mainMixerNode.outputFormatForBus(0)) { (buffer, time) -> Void in do { try self.audioFile?.writeFromBuffer(buffer) } catch let error as NSError { NSLog("Error writing %@", error.localizedDescription) }}I'm using self.engine.mainMixerNode.outputFormatForBus(0).settingswhen creating the audio file since Apple states that "The buffer format MUST match the file's processing format which is why outputFormatForBus: was used when creating the AVAudioFile object above". In the documentation for installTapOnBus they also say this: " The tap and connection formats (if non-nil) on the specified bus should be identical"However, this gives me a very large, uncompressed audio file. I want to save the file as .m4a but don't understand where to specify the settings I want to use:[AVFormatIDKey: NSNumber(unsignedInt: kAudioFormatMPEG4AAC),AVSampleRateKey : NSNumber(double: 32000.0),AVNumberOfChannelsKey: NSNumber(int: 1),AVEncoderBitRatePerChannelKey: NSNumber(int: 16),AVEncoderAudioQualityKey: NSNumber(int: Int32(AVAudioQuality.High.rawValue))]If I pass in these settings instead when creating the audio file, the app crashes when I record.Any suggestions or ideas on how to solve this?
5
1
8.9k
Jan ’22
AVPlayer and Cookie Expiration
Hi,I have some questions about how AVPlayer handles updates of a cookie's expiration time.We do something like this:1) Send a GET request to server which sets authentication cookie. This cookie has a short expiration time, CookieExpiryTime.2) Start AVPlayer. The authentication cookie is included in the AES key request.3) Every n minutes (where n is CookieExpiryTime/2), send new GET request to authentication server to get updated cookie expiration time. By logging all cookies in NSHTTPCookieStorage.sharedHTTPCookieStorage() we can see that the expiration time of the cookie is updated.The problem:When a key is requested after the expiration time of the first cookie from 1), the cookie is no longer included in the AES key request.But shouldn't the updated cookie (with extended expiration time) be considered?Question 1) Does AVPlayer filter out expired cookies when doing the AES key requests?Question 2) Does AVPlayer check NSHTTPCookieStorage.sharedHTTPCookieStorage() for updated cookies after init?Thanks,Anders
1
0
1.7k
Apr ’22
Change Mic output format in AVAudioEngine
I need to get the microphone output in a certain format that isn't equal to the hw format. To do this, I'm creating a AVAudioMixerNode which will have that format as it's output. However, I never receive any buffers when installing the tap on the mixer node. I thought the inputNode would flow upstream? Am I doing something wrong? Note that I'm not using AudioUnits or AudioQueues because I need to do some frequency filtering on the actual audio stream and thought this was the easiest way to do it.Here's the code:mixerNode = [[AVAudioMixerNode alloc]init]; //Attach node [theEngine attachNode:mixerNode]; //Then connect inputNode (mic) to mixer node [theEngine connect:theEngine.inputNode to:mixerNode format:[theEngine.inputNode outputFormatForBus:0]]; [theEngine startAndReturnError:&theError]; //Now set up the real audio format i want AudioStreamBasicDescription audioFormat; audioFormat.mSampleRate = 8000; audioFormat.mChannelsPerFrame = numberOfChannels; audioFormat.mFormatID = kAudioFormatLinearPCM; audioFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger; audioFormat.mBitsPerChannel = 16; audioFormat.mBytesPerPacket = audioFormat.mBytesPerFrame = (audioFormat.mBitsPerChannel / 8) * audioFormat.mChannelsPerFrame; audioFormat.mFramesPerPacket = 1; //Now install the tap on the mixer so we get the correct format [mixerNode installTapOnBus:0 bufferSize:4096 format:[[AVAudioFormat alloc]initWithStreamDescription:&audioFormat] block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) { NSLog(@"got buff"); }];
2
0
1.6k
Sep ’21
AVPlayer plays audio but video freezes
I have two UIViewControllers each with an AVPlayer that are supposed to play a video file when they are pushed into a UINavigationController: -(void)viewWillAppear:(BOOL)animated{ videoView = [[UIView alloc]initWithFrame:self.view.frame]; NSString *filepath = [[NSBundle mainBundle] pathForResource:@"myVideo" ofType:@"mov"]; NSURL *fileURL = [NSURL fileURLWithPath:filepath]; self.avPlayer = [AVPlayer playerWithURL:fileURL]; AVPlayerLayer *foregroundLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer]; self.avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone; foregroundLayer.frame = self.view.frame; foregroundLayer.videoGravity = AVLayerVideoGravityResizeAspectFill; [videoView.layer addSublayer:foregroundLayer]; [self.view addSubview:videoView]; self.avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:[self.avPlayer currentItem]]; } -(void)viewDidAppear:(BOOL)animated{ [self.avPlayer play]; } -(void)playerItemDidReachEnd:(NSNotification *)notification { [self.navigationController popViewControllerAnimated:NO] }The first time I push any of the UIViewControllers the playback works well. But after that, if I push any of them again the sound plays but the video freezes.I've tried using a MPMoviePlayerViewController but the behavior is the same. Any thoughts?
13
0
12k
Sep ’22
AudioConverterFillComplexBuffer crash (NativeInt16ToFloat32Scaled_ARM)
Here is the process in My application.Mic -> AVCaptureOutput -> Audio(PCM) -> Audio Encoder -> AAC Packet (Encoded)Camera -> AVCaptureOutput -> Image -> Video Encoder -> H.264 Video Packet.(Encoded)So, My App is Movie Encoder.Crash is happened when camera is switched. (Front Camera <-> Back Camera)Crash line is AudioConverterFillComplexBuffer.maybe NativeInt16ToFloat32Scaled_ARM..what does that mean??? why???0 AudioCodecs 0x0000000183fbe2bc NativeInt16ToFloat32Scaled_ARM + 1321 AudioCodecs 0x0000000183f63708 AppendInputData(void*, void const*, unsigned int*, unsigned int*, AudioStreamPacketDescription const*) + 562 AudioToolbox 0x000000018411aaac CodecConverter::AppendExcessInput(unsigned int&) + 1963 AudioToolbox 0x000000018411a59c CodecConverter::EncoderFillBuffer(unsigned int&, AudioBufferList&, AudioStreamPacketDescription*) + 6604 AudioToolbox 0x0000000184124ec0 AudioConverterChain::RenderOutput(CABufferList*, unsigned int, unsigned int&, AudioStreamPacketDescription*) + 1165 AudioToolbox 0x0000000184100d98 BufferedAudioConverter::FillBuffer(unsigned int&, AudioBufferList&, AudioStreamPacketDescription*) + 4446 AudioToolbox 0x00000001840d8c9c AudioConverterFillComplexBuffer + 3407 MovieEncoder 0x0000000100341fd4 __49-[AACEncoder encodeSampleBuffer:completionBlock:]_block_invoke (AACEncoder.m:247)
1
1
1.3k
Sep ’23
What do error code "-12642" and "-12785" mean?
I am working on a video app and from time to time I get error like this:"The operation could not be completed. An unknown error occured (-12642)""The operation could not be completed. An unknown error occured (-12875)"I couldn't find the map of the AVPlayer error code anywhere online. Does anyone know where I can get the error descriptions of all the -12xxx code?Thanks!
9
0
13k
Jun ’22
Playing slow motion videos from camera make it loses slow motion effect
So, I've never faced a problem like this for so long. I have basically scrutinized every possible website on the internet looking for a solution but have found nothing so far.I have a custom picker controller in which I can select videos and play them. Beforehand, I was struggling to play slow motion videos (only no-slow-motion videos were playing) but after searching I found the solution here.http://stackoverflow.com/questions/26152396/how-to-access-nsdata-nsurl-of-slow-motion-videos-using-photokitSo, my code to get videos became this:let videoOptions = PHVideoRequestOptions() videoOptions.version = PHVideoRequestOptionsVersion.Original PHImageManager.defaultManager().requestAVAssetForVideo(asset!, options: videoOptions , resultHandler: { (asset, audioMix, info) -> Void in if let asset = asset as? AVURLAsset { let videoData = NSData(contentsOfURL: asset.URL) let videoPath = NSTemporaryDirectory() + "tmpMovie.MOV" let videoURL = NSURL(fileURLWithPath: videoPath) let writeResult = videoData?.writeToURL(videoURL, atomically: true) if let writeResult = writeResult where writeResult { print("success") let videoVC = VideoViewController(videoUrl: videoURL) imagePicker.presentViewController(videoVC, animated: false, completion: nil) } else { print("failure") } } }) Now, slow motion videos are playing but in a normal way instead of in a slow-motion way. This questions relates to the problem.https://devforums.apple.com/message/903937#903937I've seen a lot of comments saying they solved the problem by using Photos framework, but I have no idea how to achieve this and they didn't explain either. It might be something to do PHAssetMediaSubtypeVideoHighFrameRate. So, how would be possible to play slow motion videos? Do I need to change the fps somehow?Please help, I am quite desperate :/ Objective-C code is welcome as well.
4
0
2.6k
Jun ’23
How to get frame times and/or stepping through video?
For evaluation of physical phenomena recorded on video we need to know the exact timestamps of the recorded frames and stepping frame by frame.Converting from frame number to timestamp using the framerate did not work because in many videos recorded with iOS cameras the frame rate slightly jitters. Using seekToTime and equivalent methods therefore caused skipping oder doubling of frames.How is it possible to get the exact time(stamps) of every frame in a video using AVFoundation and stepping/seeking through a video on per-frame basis?AVPlayerItem seems to be the only way I found so far to step on per-frame basis, but is it the right choice?Is there any other method?
9
0
9.7k
Dec ’22
AVAudioConnectionPoint creates gaps when writing to file
I'm using AVAudioEngine to record input from the microphone as well as various sound effects to a single file.My AVAudioEngine graph looks like this:soundfileNode ----> mainMixer ---> outputNode (speaker) | | (AVAudioConnectionPoint) v inputNode (mic) --> secondaryMixer ---> tap (write to file)I'm splitting the output from my mainMixer using AVAudioConnectionPoints to make it output audio to a secondaryMixer and to the speaker. I'm doing this so that only the sound from the sound file nodes are played back through the speaker while recording, as I don't want the mic input to be heard during recording.The error occurs when the output from the mainMixer is written to an audio file using a tap I have installed on the secondaryMixer. The recorded sound "stutters" - there is a very short silence - or gap - about 3 times every second, which probably occurs every time my tap closure is called. It's as if not the entire buffer is written to the output file. The sound from the mic is written to the file exactly as it should, with no gaps, so the problem seems to be the AVAudioConnectionPoint from the mainMixer to the secondaryMixer, which isn't in complete sync or drops parts of the buffer.Has anyone else experienced this problem?
6
0
1.6k
Aug ’21
Issue with Audio Queue Implementation
# I amtrying to implement real-time streaming of voice i.e., here we need to records voice as small chunks# I tried to implement this using AudioQueue concept in Objective-C.# But , the app crashes when trying to record the voice. It crashes when callback method is called for recording.# I have attached sample code snippet which I’ve used for implementation. Please help me in resolving the issue- (void)startRecording { [self setupAudioFormat:&recordState.dataFormat]; recordState.currentPacket = 0; OSStatus status; status = AudioQueueNewInput(&recordState.dataFormat, AudioInputCallback, &recordState, CFRunLoopGetCurrent(), kCFRunLoopCommonModes, 0, &recordState.queue); if (status == 0) { // Prime recording buffers with empty data for (int i = 0; i < NUM_BUFFERS; i++) { AudioQueueAllocateBuffer(recordState.queue, 16000, &recordState.buffers[i]); AudioQueueEnqueueBuffer (recordState.queue, recordState.buffers[i], 0, NULL); } status = AudioFileCreateWithURL(fileURL, kAudioFileAIFFType, &recordState.dataFormat, kAudioFileFlags_EraseFile, &recordState.audioFile); if (status == 0) { recordState.recording = true; status = AudioQueueStart(recordState.queue, NULL); if (status == 0) { //labelStatus.text = @"Recording"; } } } if (status != 0) { [self stopRecording]; //labelStatus.text = @"Record Failed"; } } void AudioInputCallback(void * inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer, const AudioTimeStamp * inStartTime, UInt32 inNumberPacketDescriptions, const AudioStreamPacketDescription * inPacketDescs) { RecordState * recordState = (RecordState*)inUserData; if (!recordState->recording) { printf("Not recording, returning\n"); } // if (inNumberPacketDescriptions == 0 && recordState->dataFormat.mBytesPerPacket != 0) // { // inNumberPacketDescriptions = inBuffer->mAudioDataByteSize / recordState->dataFormat.mBytesPerPacket; // } printf("Writing buffer %lld\n", recordState->currentPacket); OSStatus status = AudioFileWritePackets(recordState->audioFile, false, inBuffer->mAudioDataByteSize, inPacketDescs, recordState->currentPacket, &inNumberPacketDescriptions, inBuffer->mAudioData); if (status == 0) { recordState->currentPacket += inNumberPacketDescriptions; } AudioQueueEnqueueBuffer(recordState->queue, inBuffer, 0, NULL); } -void)setupAudioFormat:(AudioStreamBasicDescription*)format { format->mSampleRate = 8000.0; format->mFormatID = kAudioFormatLinearPCM; format->mFramesPerPacket = 1; format->mChannelsPerFrame = 1; format->mBytesPerFrame = 2; format->mBytesPerPacket = 2; format->mBitsPerChannel = 16; format->mReserved = 0; format->mFormatFlags = kLinearPCMFormatFlagIsBigEndian | kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked; }
3
0
1.5k
Feb ’23
AVPlayer pause live stream on iOS 9.3
Hi everyone!Im having difficulties trying to resume live stream playback from previously paused moment.On iOS 9.2 and below player continued to play from paused moment.On iOS 9.3 and above, when i resume playing, i receive "playerBufferEmpty" and AVPlayerItemTimeJumpedNotification, and as a result playback doesnt continue from the paused moment.This looks like an issue in AVPlayer since everything works on iOS versions 9.2 and below. I also tried playerItem.canUseNetworkResourcesForLiveStreamingWhilePaused , but it doesnt help.Are there any changes in AVPlayer/AVPlayerItem regarding this from iOS 9.2 to iOS 9.3?Thanks!
6
0
2.8k
Oct ’21
Processing / tapping an HLS audio stream (or global app output)
I'm trying to do some realtime audio processing on audio served from an HLS stream (i.e. an AVPlayer created using an M3U HTTP URL). It doesn't seem like attaching an AVAudioMix configured with with an `audioTapProcessor` has any effect; none of the callbacks except `init` are being invoked. Is this a known limitation? If so, is this documented somewhere?If the above is a limitation, what are my options using some of the other audio APIs? I looked into `AVAudioEngine` as well but it doesn't seem like there's any way I can configure any of the input node types to use an HLS stream. Am I wrong? Are there lower level APIs available to play HLS streams that provide the necessary hooks?Alternatively, is there some generic way to tap into all audio being output by my app regardless of its source?Thanks a lot!
11
0
5.1k
Sep ’23
Bluetooth with AVAudioSessionPlaybackAndRecord
Hello!I am working on an app that plays audio and accepts voice commands simultaniously. When I play audio through bluetooth in my car, the Audio Session for the app uses the Bluetooth HFP ports. This causes the output audio quality to become very poor. If I switch to AVAudioSessionPlayback, the output is on the A2DP port, which sounds great. Ideally I would like to be able to play ouput through A2DP, and accept input through HFP, but I assume this is a limitation of bluetooth, or everything would already work this way to improve sound quality. For my app it would be acceptable to accept input from the phone's microphone, and play the audio through bluetooth, but this also seems impossible as described here: http://stackoverflow.com/questions/22146406/ios-input-mic-output-bluetooth-device. Any advice on improving playback audio quality when connected to bluetooth while using AVAudioSessionPlayback and record would be greatly appreciated. Has anyone encounted this issue before and had a suitable fix?Thanks!
Replies
3
Boosts
0
Views
5.0k
Activity
Oct ’21
AVAudioRecorder and audio data file offset
I'm trying to get a wav file to outside API from iOS. I've managed to do the file and post it from iPhone but the service doesn't take it (API errors are not helpful either). I've managed to track down the difference between a file I manage to send to the service and the file save with iPhone to audio data file offset parameter. afinfo command gives the working file value 44 and iOS saved audiofile has 4096. Is there any way to change this to 44 also on iOS?My current settings for AVAudioRecorder:let recordSettings = [ AVNumberOfChannelsKey: 1, AVSampleRateKey: 16000.0, AVFormatIDKey: kAudioFormatLinearPCM, AVLinearPCMBitDepthKey: 8, AVLinearPCMIsBigEndianKey: false, AVLinearPCMIsFloatKey: false, AVLinearPCMIsNonInterleaved: false ]
Replies
2
Boosts
0
Views
1.1k
Activity
Apr ’23
CMSampleBufferSetDataBufferFromAudioBufferList returning -12731
I am trying to take a video file read it in using AVAssetReader and pass the audio off to CoreAudio for processing (adding effects and stuff) before saving it back out to disk using AVAssetWriter. I would like to point out that if i set the componentSubType on AudioComponentDescription of my output node as RemoteIO, things play correctly though the speakers. This makes me confident that my AUGraph is properly setup as I can hear things working. I am setting the subType to GenericOutput though so I can do the rendering myself and get back the adjusted audio.I am reading in the audio and i pass the CMSampleBufferRef off to copyBuffer. This puts the audio into a circular buffer that will be read in later.- (void)copyBuffer:(CMSampleBufferRef)buf { if (_readyForMoreBytes == NO) { return; } AudioBufferList abl; CMBlockBufferRef blockBuffer; CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(buf, NULL, &abl, sizeof(abl), NULL, NULL, kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment, &blockBuffer); UInt32 size = (unsigned int)CMSampleBufferGetTotalSampleSize(buf); BOOL bytesCopied = TPCircularBufferProduceBytes(&circularBuffer, abl.mBuffers[0].mData, size); if (!bytesCopied){ / _readyForMoreBytes = NO; if (size > kRescueBufferSize){ NSLog(@"Unable to allocate enought space for rescue buffer, dropping audio frame"); } else { if (rescueBuffer == nil) { rescueBuffer = malloc(kRescueBufferSize); } rescueBufferSize = size; memcpy(rescueBuffer, abl.mBuffers[0].mData, size); } } CFRelease(blockBuffer); if (!self.hasBuffer && bytesCopied > 0) { self.hasBuffer = YES; } }Next I call processOutput. This will do a manual reder on the outputUnit. When AudioUnitRender is called it invokes the playbackCallback below, which is what is hooked up as input callback on my first node. playbackCallback pulls the data off the circular buffer and feeds it into the audioBufferList passed in. Like I said before if the output is set as RemoteIO this will cause the audio to correctly be played on the speakers. When AudioUnitRender finishes, it returns noErr and the bufferList object contains valid data. When I call CMSampleBufferSetDataBufferFromAudioBufferList though I get kCMSampleBufferError_RequiredParameterMissing (-12731).-(CMSampleBufferRef)processOutput { if(self.offline == NO) { return NULL; } AudioUnitRenderActionFlags flags = 0; AudioTimeStamp inTimeStamp; memset(&inTimeStamp, 0, sizeof(AudioTimeStamp)); inTimeStamp.mFlags = kAudioTimeStampSampleTimeValid; UInt32 busNumber = 0; UInt32 numberFrames = 512; inTimeStamp.mSampleTime = 0; UInt32 channelCount = 2; AudioBufferList *bufferList = (AudioBufferList*)malloc(sizeof(AudioBufferList)+sizeof(AudioBuffer)*(channelCount-1)); bufferList->mNumberBuffers = channelCount; for (int j=0; j<channelCount; j++) { AudioBuffer buffer = {0}; buffer.mNumberChannels = 1; buffer.mDataByteSize = numberFrames*sizeof(SInt32); buffer.mData = calloc(numberFrames,sizeof(SInt32)); bufferList->mBuffers[j] = buffer; } CheckError(AudioUnitRender(outputUnit, &flags, &inTimeStamp, busNumber, numberFrames, bufferList), @"AudioUnitRender outputUnit"); CMSampleBufferRef sampleBufferRef = NULL; CMFormatDescriptionRef format = NULL; CMSampleTimingInfo timing = { CMTimeMake(1, 44100), kCMTimeZero, kCMTimeInvalid }; AudioStreamBasicDescription audioFormat = self.audioFormat; CheckError(CMAudioFormatDescriptionCreate(kCFAllocatorDefault, &audioFormat, 0, NULL, 0, NULL, NULL, &format), @"CMAudioFormatDescriptionCreate"); CheckError(CMSampleBufferCreate(kCFAllocatorDefault, NULL, false, NULL, NULL, format, numberFrames, 1, &timing, 0, NULL, &sampleBufferRef), @"CMSampleBufferCreate"); CheckError(CMSampleBufferSetDataBufferFromAudioBufferList(sampleBufferRef, kCFAllocatorDefault, kCFAllocatorDefault, 0, bufferList), @"CMSampleBufferSetDataBufferFromAudioBufferList"); return sampleBufferRef; }static OSStatus playbackCallback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { int numberOfChannels = ioData->mBuffers[0].mNumberChannels; SInt16 *outSample = (SInt16 *)ioData->mBuffers[0].mData; / memset(outSample, 0, ioData->mBuffers[0].mDataByteSize); MyAudioPlayer *p = (__bridge MyAudioPlayer *)inRefCon; if (p.hasBuffer){ int32_t availableBytes; SInt16 *bufferTail = TPCircularBufferTail([p getBuffer], &availableBytes); int32_t requestedBytesSize = inNumberFrames * kUnitSize * numberOfChannels; int bytesToRead = MIN(availableBytes, requestedBytesSize); memcpy(outSample, bufferTail, bytesToRead); TPCircularBufferConsume([p getBuffer], bytesToRead); if (availableBytes <= requestedBytesSize*2){ [p setReadyForMoreBytes]; } if (availableBytes <= requestedBytesSize) { p.hasBuffer = NO; } } return noErr; }The CMSampleBufferRef I pass in looks valid (below is a dump of the object from the debugger)CMSampleBuffer 0x7f87d2a03120 retainCount: 1 allocator: 0x103333180 invalid = NO dataReady = NO makeDataReadyCallback = 0x0 makeDataReadyRefcon = 0x0 formatDescription = <CMAudioFormatDescription 0x7f87d2a02b20 [0x103333180]> { mediaType:'soun' mediaSubType:'lpcm' mediaSpecific: { ASBD: { mSampleRate: 44100.000000 mFormatID: 'lpcm' mFormatFlags: 0xc2c mBytesPerPacket: 2 mFramesPerPacket: 1 mBytesPerFrame: 2 mChannelsPerFrame: 1 mBitsPerChannel: 16 } cookie: {(null)} ACL: {(null)} } extensions: {(null)} } sbufToTrackReadiness = 0x0 numSamples = 512 sampleTimingArray[1] = { {PTS = {0/1 = 0.000}, DTS = {INVALID}, duration = {1/44100 = 0.000}}, } dataBuffer = 0x0The buffer list looks like thisPrinting description of bufferList: (AudioBufferList *) bufferList = 0x00007f87d280b0a0 Printing description of bufferList->mNumberBuffers: (UInt32) mNumberBuffers = 2 Printing description of bufferList->mBuffers: (AudioBuffer [1]) mBuffers = { [0] = (mNumberChannels = 1, mDataByteSize = 2048, mData = 0x00007f87d3008c00) }Really at a loss here, hoping someone can help. Thanks,In case it matters i am debuggin this in ios 8.3 simulator and the audio is coming from a mp4 that i shot on my iphone 6 then saved to my laptop.
Replies
4
Boosts
0
Views
6.8k
Activity
Aug ’21
Can Audio Unit latency be updated after initialization?
I'm having trouble updating kAudioUnitProperty_Latency in an AU after the plugin has been initialized. Just sending property changed events to the AU host for kAudioUnitProperty_Latency does not seem to do the trick in Logic Pro X, and I can't find a good way to make it reset.I'm aware that a host can't really seamlessly change the latency compensation, but I'm fine with glitches since this is not something that happens a lot (and definitely not possible to automate or anything like that).Is it at all possible? I really want to avoid having a fixed large delay and compensate internally. (Not because of the complexity, but because I don't want to add more latency than needed in the general case.)
Replies
3
Boosts
0
Views
1.3k
Activity
Oct ’21
Random AVAudioEngine crash
I am seeing a random crash on the AVAudioEngine startAndReturnError method call. I am not able to reproduce this but I am getting a lot of crash reports from the application on the store. My application mix audio from mulitiple files which I pretty much copy the code from the sample project UsingAVAudioEngineforPlaybackMixingandRecording. I tried to add try-catch block to the call and it does not seem to catch the exception. Any ideas or suggestion on how to debug this? It happens across device models (iPhone, iPad, iPod) and iOS (8 and 9)Thread : Fatal Exception: com.apple.coreaudio.avfaudio0 CoreFoundation 0x23d9468b __exceptionPreprocess1 libobjc.A.dylib 0x35292e17 objc_exception_throw2 CoreFoundation 0x23d94561 +[NSException raise:format:]3 libAVFAudio.dylib 0x22652c21 AVAE_RaiseException(NSString*, ...)4 libAVFAudio.dylib 0x22665dd5 AVAudioEngineGraph::PerformCommand(AUGraphNode&, AVAudioEngineGraph::ENodeCommand, void*, unsigned long) const5 libAVFAudio.dylib 0x226669e3 AVAudioEngineGraph::Initialize()6 libAVFAudio.dylib 0x226a3cc3 AVAudioEngineImpl::Initialize()7 libAVFAudio.dylib 0x226a2bdf AVAudioEngineImpl::Start(NSError**)8 libAVFAudio.dylib 0x226a2b53 -[AVAudioEngine startAndReturnError:]9 Acapella 0x000bd98b __33-[MCAudioMixer initWithMetadata:]_block_invoke (MCAudioMixer.m:182)10 Foundation 0x24b48b39 __22-[__NSObserver _doit:]_block_invoke11 Foundation 0x24b4c80d __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__12 Foundation 0x24aae217 -[NSBlockOperation main]13 Foundation 0x24aa04e1 -[__NSOperationInternal _start:]14 Foundation 0x24b4eac5 __NSOQSchedule_f15 libdispatch.dylib 0x35994d17 _dispatch_client_callout16 libdispatch.dylib 0x359a30b1 _dispatch_main_queue_callback_4CF$VARIANT$mp17 CoreFoundation 0x23d579ad __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__18 CoreFoundation 0x23d55ea7 __CFRunLoopRun19 CoreFoundation 0x23ca9249 CFRunLoopRunSpecific20 CoreFoundation 0x23ca9035 CFRunLoopRunInMode21 GraphicsServices 0x2cd5bad1 GSEventRunModal22 UIKit 0x27ebe8a9 UIApplicationMain23 Acapella 0x0015fc63 main (main.m:14)24 libdyld.dylib 0x359de873 start
Replies
7
Boosts
1
Views
5.7k
Activity
Mar ’22
AVCaptureDevice: Camera frame rate off...
It seems the camera produces unexpected results in terms of not quite matching the frame rate given. Specifically, if I set my AVCaptureDevice's activeVideoMaxFrameDuration and activeVideoMinFrameDuration to a CMTimeMake(1,30) I get a frame rate of 30.02 Hz. More curiously, if I set it to CMTimeMake(100,2997), I get a frame rate of 29.02 Hz, so almost an entire Hz or 3% off. At CMTimeMake(1,25) I get 25.01 Hz, and at CMTimeMake(1,24) I get 24.01 Hz. The times are measured by the frames' CMSampleBufferGetPresentationTimeStamp(). So for the round numbers, I'm about 0.1% off and for 29.97 Hz I'm 3% off. 0.1% may not sound like much, but if I want to record at a fixed standard frame rate it means a lost or extra frame every other minute. This happens both on iPhone 6 and on iPhone 6S, and the numbers were obtained in the 1080p 2-60Hz mode. To explore the oddity yet a bit further, at CMTimeMake(100,2999) I get 29.03 Hz and at CMTimeMake(100,3001) I get 30.02 Hz. So it could be that the camera only supports multiples of 1 Hz frame rate intervals, but not exactly.To satisfy my curiousity, I wrote a PLL stabilization around the camera that changes the frame rate depending on whether the video stream is currently ahead or behind where it should be, and that sort of works, but only if cinematic stabilization is off, and that also doesn't feel like the right way to use the built-in camera. Am I missing something? In particular, the result where for the 29.97 specification I'm getting 29 Hz seems really odd, given that this is a very common frame rate. Obviously a phone isn't a true real-time operating system and I don't mind individual frames being off a little bit, but there should be enough regulation around it so as not to cause missed frames if I record for a while.
Replies
2
Boosts
0
Views
1.3k
Activity
Apr ’23
Creating a new MIDI control surface mapping driver for Logic Pro X
We need to developpe a new "control surface mapping driver" for Logic Pro X, to match the "simple" fonctionnal requiements of our Tangerine Automation InterfaceI'm trying to find the info on how to create the "mapping driver" that will translate our interface "hardware/midi mapping" to Logic Pro X internal controllers acces. (volume, mutes, automation modes etc...)Ou interface is already reconnized as 5 ports Plug&Play USB midi device. It can be used with the HUI mapping in Logic Pro x but we want to get better control behavior, with our own mapping Any pointer on where to look in the apple developer section would be appriciateddbmdbu
Replies
5
Boosts
0
Views
4.3k
Activity
Nov ’21
Using AVAudioEngine to record to compressed file
I'm trying to use AVAudioEngine to record sounds from the microphone together with various sound effect files to a AVAudioFile.I create an AVAudioFile like this:let settings = self.engine.mainMixerNode.outputFormatForBus(0).settingstry self.audioFile = AVAudioFile(forWriting: self.audioURL, settings: settings, commonFormat: .PCMFormatFloat32, interleaved: false)I install a tap on the audio engine's mainMixerNode, where I write the buffer to the file:self.engine.mainMixerNode.installTapOnBus(0, bufferSize: 4096, format: self.engine.mainMixerNode.outputFormatForBus(0)) { (buffer, time) -> Void in do { try self.audioFile?.writeFromBuffer(buffer) } catch let error as NSError { NSLog("Error writing %@", error.localizedDescription) }}I'm using self.engine.mainMixerNode.outputFormatForBus(0).settingswhen creating the audio file since Apple states that "The buffer format MUST match the file's processing format which is why outputFormatForBus: was used when creating the AVAudioFile object above". In the documentation for installTapOnBus they also say this: " The tap and connection formats (if non-nil) on the specified bus should be identical"However, this gives me a very large, uncompressed audio file. I want to save the file as .m4a but don't understand where to specify the settings I want to use:[AVFormatIDKey: NSNumber(unsignedInt: kAudioFormatMPEG4AAC),AVSampleRateKey : NSNumber(double: 32000.0),AVNumberOfChannelsKey: NSNumber(int: 1),AVEncoderBitRatePerChannelKey: NSNumber(int: 16),AVEncoderAudioQualityKey: NSNumber(int: Int32(AVAudioQuality.High.rawValue))]If I pass in these settings instead when creating the audio file, the app crashes when I record.Any suggestions or ideas on how to solve this?
Replies
5
Boosts
1
Views
8.9k
Activity
Jan ’22
AVPlayer and Cookie Expiration
Hi,I have some questions about how AVPlayer handles updates of a cookie's expiration time.We do something like this:1) Send a GET request to server which sets authentication cookie. This cookie has a short expiration time, CookieExpiryTime.2) Start AVPlayer. The authentication cookie is included in the AES key request.3) Every n minutes (where n is CookieExpiryTime/2), send new GET request to authentication server to get updated cookie expiration time. By logging all cookies in NSHTTPCookieStorage.sharedHTTPCookieStorage() we can see that the expiration time of the cookie is updated.The problem:When a key is requested after the expiration time of the first cookie from 1), the cookie is no longer included in the AES key request.But shouldn't the updated cookie (with extended expiration time) be considered?Question 1) Does AVPlayer filter out expired cookies when doing the AES key requests?Question 2) Does AVPlayer check NSHTTPCookieStorage.sharedHTTPCookieStorage() for updated cookies after init?Thanks,Anders
Replies
1
Boosts
0
Views
1.7k
Activity
Apr ’22
Change Mic output format in AVAudioEngine
I need to get the microphone output in a certain format that isn't equal to the hw format. To do this, I'm creating a AVAudioMixerNode which will have that format as it's output. However, I never receive any buffers when installing the tap on the mixer node. I thought the inputNode would flow upstream? Am I doing something wrong? Note that I'm not using AudioUnits or AudioQueues because I need to do some frequency filtering on the actual audio stream and thought this was the easiest way to do it.Here's the code:mixerNode = [[AVAudioMixerNode alloc]init]; //Attach node [theEngine attachNode:mixerNode]; //Then connect inputNode (mic) to mixer node [theEngine connect:theEngine.inputNode to:mixerNode format:[theEngine.inputNode outputFormatForBus:0]]; [theEngine startAndReturnError:&theError]; //Now set up the real audio format i want AudioStreamBasicDescription audioFormat; audioFormat.mSampleRate = 8000; audioFormat.mChannelsPerFrame = numberOfChannels; audioFormat.mFormatID = kAudioFormatLinearPCM; audioFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger; audioFormat.mBitsPerChannel = 16; audioFormat.mBytesPerPacket = audioFormat.mBytesPerFrame = (audioFormat.mBitsPerChannel / 8) * audioFormat.mChannelsPerFrame; audioFormat.mFramesPerPacket = 1; //Now install the tap on the mixer so we get the correct format [mixerNode installTapOnBus:0 bufferSize:4096 format:[[AVAudioFormat alloc]initWithStreamDescription:&audioFormat] block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) { NSLog(@"got buff"); }];
Replies
2
Boosts
0
Views
1.6k
Activity
Sep ’21
AVPlayer plays audio but video freezes
I have two UIViewControllers each with an AVPlayer that are supposed to play a video file when they are pushed into a UINavigationController: -(void)viewWillAppear:(BOOL)animated{ videoView = [[UIView alloc]initWithFrame:self.view.frame]; NSString *filepath = [[NSBundle mainBundle] pathForResource:@"myVideo" ofType:@"mov"]; NSURL *fileURL = [NSURL fileURLWithPath:filepath]; self.avPlayer = [AVPlayer playerWithURL:fileURL]; AVPlayerLayer *foregroundLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer]; self.avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone; foregroundLayer.frame = self.view.frame; foregroundLayer.videoGravity = AVLayerVideoGravityResizeAspectFill; [videoView.layer addSublayer:foregroundLayer]; [self.view addSubview:videoView]; self.avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:[self.avPlayer currentItem]]; } -(void)viewDidAppear:(BOOL)animated{ [self.avPlayer play]; } -(void)playerItemDidReachEnd:(NSNotification *)notification { [self.navigationController popViewControllerAnimated:NO] }The first time I push any of the UIViewControllers the playback works well. But after that, if I push any of them again the sound plays but the video freezes.I've tried using a MPMoviePlayerViewController but the behavior is the same. Any thoughts?
Replies
13
Boosts
0
Views
12k
Activity
Sep ’22
AudioConverterFillComplexBuffer crash (NativeInt16ToFloat32Scaled_ARM)
Here is the process in My application.Mic -> AVCaptureOutput -> Audio(PCM) -> Audio Encoder -> AAC Packet (Encoded)Camera -> AVCaptureOutput -> Image -> Video Encoder -> H.264 Video Packet.(Encoded)So, My App is Movie Encoder.Crash is happened when camera is switched. (Front Camera <-> Back Camera)Crash line is AudioConverterFillComplexBuffer.maybe NativeInt16ToFloat32Scaled_ARM..what does that mean??? why???0 AudioCodecs 0x0000000183fbe2bc NativeInt16ToFloat32Scaled_ARM + 1321 AudioCodecs 0x0000000183f63708 AppendInputData(void*, void const*, unsigned int*, unsigned int*, AudioStreamPacketDescription const*) + 562 AudioToolbox 0x000000018411aaac CodecConverter::AppendExcessInput(unsigned int&) + 1963 AudioToolbox 0x000000018411a59c CodecConverter::EncoderFillBuffer(unsigned int&, AudioBufferList&, AudioStreamPacketDescription*) + 6604 AudioToolbox 0x0000000184124ec0 AudioConverterChain::RenderOutput(CABufferList*, unsigned int, unsigned int&, AudioStreamPacketDescription*) + 1165 AudioToolbox 0x0000000184100d98 BufferedAudioConverter::FillBuffer(unsigned int&, AudioBufferList&, AudioStreamPacketDescription*) + 4446 AudioToolbox 0x00000001840d8c9c AudioConverterFillComplexBuffer + 3407 MovieEncoder 0x0000000100341fd4 __49-[AACEncoder encodeSampleBuffer:completionBlock:]_block_invoke (AACEncoder.m:247)
Replies
1
Boosts
1
Views
1.3k
Activity
Sep ’23
What do error code "-12642" and "-12785" mean?
I am working on a video app and from time to time I get error like this:"The operation could not be completed. An unknown error occured (-12642)""The operation could not be completed. An unknown error occured (-12875)"I couldn't find the map of the AVPlayer error code anywhere online. Does anyone know where I can get the error descriptions of all the -12xxx code?Thanks!
Replies
9
Boosts
0
Views
13k
Activity
Jun ’22
Anyone know what kind of video can support a transparent background?
I just learned that MP4 files don't support alpha channel / transparent backgrounds. I'd like to play a logo animation over a UIView.Has anyone successfully done this, and/or can point me in a direction? Thank you.
Replies
5
Boosts
0
Views
6.6k
Activity
Apr ’22
Playing slow motion videos from camera make it loses slow motion effect
So, I've never faced a problem like this for so long. I have basically scrutinized every possible website on the internet looking for a solution but have found nothing so far.I have a custom picker controller in which I can select videos and play them. Beforehand, I was struggling to play slow motion videos (only no-slow-motion videos were playing) but after searching I found the solution here.http://stackoverflow.com/questions/26152396/how-to-access-nsdata-nsurl-of-slow-motion-videos-using-photokitSo, my code to get videos became this:let videoOptions = PHVideoRequestOptions() videoOptions.version = PHVideoRequestOptionsVersion.Original PHImageManager.defaultManager().requestAVAssetForVideo(asset!, options: videoOptions , resultHandler: { (asset, audioMix, info) -> Void in if let asset = asset as? AVURLAsset { let videoData = NSData(contentsOfURL: asset.URL) let videoPath = NSTemporaryDirectory() + "tmpMovie.MOV" let videoURL = NSURL(fileURLWithPath: videoPath) let writeResult = videoData?.writeToURL(videoURL, atomically: true) if let writeResult = writeResult where writeResult { print("success") let videoVC = VideoViewController(videoUrl: videoURL) imagePicker.presentViewController(videoVC, animated: false, completion: nil) } else { print("failure") } } }) Now, slow motion videos are playing but in a normal way instead of in a slow-motion way. This questions relates to the problem.https://devforums.apple.com/message/903937#903937I've seen a lot of comments saying they solved the problem by using Photos framework, but I have no idea how to achieve this and they didn't explain either. It might be something to do PHAssetMediaSubtypeVideoHighFrameRate. So, how would be possible to play slow motion videos? Do I need to change the fps somehow?Please help, I am quite desperate :/ Objective-C code is welcome as well.
Replies
4
Boosts
0
Views
2.6k
Activity
Jun ’23
How to get frame times and/or stepping through video?
For evaluation of physical phenomena recorded on video we need to know the exact timestamps of the recorded frames and stepping frame by frame.Converting from frame number to timestamp using the framerate did not work because in many videos recorded with iOS cameras the frame rate slightly jitters. Using seekToTime and equivalent methods therefore caused skipping oder doubling of frames.How is it possible to get the exact time(stamps) of every frame in a video using AVFoundation and stepping/seeking through a video on per-frame basis?AVPlayerItem seems to be the only way I found so far to step on per-frame basis, but is it the right choice?Is there any other method?
Replies
9
Boosts
0
Views
9.7k
Activity
Dec ’22
AVAudioConnectionPoint creates gaps when writing to file
I'm using AVAudioEngine to record input from the microphone as well as various sound effects to a single file.My AVAudioEngine graph looks like this:soundfileNode ----> mainMixer ---> outputNode (speaker) | | (AVAudioConnectionPoint) v inputNode (mic) --> secondaryMixer ---> tap (write to file)I'm splitting the output from my mainMixer using AVAudioConnectionPoints to make it output audio to a secondaryMixer and to the speaker. I'm doing this so that only the sound from the sound file nodes are played back through the speaker while recording, as I don't want the mic input to be heard during recording.The error occurs when the output from the mainMixer is written to an audio file using a tap I have installed on the secondaryMixer. The recorded sound "stutters" - there is a very short silence - or gap - about 3 times every second, which probably occurs every time my tap closure is called. It's as if not the entire buffer is written to the output file. The sound from the mic is written to the file exactly as it should, with no gaps, so the problem seems to be the AVAudioConnectionPoint from the mainMixer to the secondaryMixer, which isn't in complete sync or drops parts of the buffer.Has anyone else experienced this problem?
Replies
6
Boosts
0
Views
1.6k
Activity
Aug ’21
Issue with Audio Queue Implementation
# I amtrying to implement real-time streaming of voice i.e., here we need to records voice as small chunks# I tried to implement this using AudioQueue concept in Objective-C.# But , the app crashes when trying to record the voice. It crashes when callback method is called for recording.# I have attached sample code snippet which I’ve used for implementation. Please help me in resolving the issue- (void)startRecording { [self setupAudioFormat:&recordState.dataFormat]; recordState.currentPacket = 0; OSStatus status; status = AudioQueueNewInput(&recordState.dataFormat, AudioInputCallback, &recordState, CFRunLoopGetCurrent(), kCFRunLoopCommonModes, 0, &recordState.queue); if (status == 0) { // Prime recording buffers with empty data for (int i = 0; i < NUM_BUFFERS; i++) { AudioQueueAllocateBuffer(recordState.queue, 16000, &recordState.buffers[i]); AudioQueueEnqueueBuffer (recordState.queue, recordState.buffers[i], 0, NULL); } status = AudioFileCreateWithURL(fileURL, kAudioFileAIFFType, &recordState.dataFormat, kAudioFileFlags_EraseFile, &recordState.audioFile); if (status == 0) { recordState.recording = true; status = AudioQueueStart(recordState.queue, NULL); if (status == 0) { //labelStatus.text = @"Recording"; } } } if (status != 0) { [self stopRecording]; //labelStatus.text = @"Record Failed"; } } void AudioInputCallback(void * inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer, const AudioTimeStamp * inStartTime, UInt32 inNumberPacketDescriptions, const AudioStreamPacketDescription * inPacketDescs) { RecordState * recordState = (RecordState*)inUserData; if (!recordState->recording) { printf("Not recording, returning\n"); } // if (inNumberPacketDescriptions == 0 && recordState->dataFormat.mBytesPerPacket != 0) // { // inNumberPacketDescriptions = inBuffer->mAudioDataByteSize / recordState->dataFormat.mBytesPerPacket; // } printf("Writing buffer %lld\n", recordState->currentPacket); OSStatus status = AudioFileWritePackets(recordState->audioFile, false, inBuffer->mAudioDataByteSize, inPacketDescs, recordState->currentPacket, &inNumberPacketDescriptions, inBuffer->mAudioData); if (status == 0) { recordState->currentPacket += inNumberPacketDescriptions; } AudioQueueEnqueueBuffer(recordState->queue, inBuffer, 0, NULL); } -void)setupAudioFormat:(AudioStreamBasicDescription*)format { format->mSampleRate = 8000.0; format->mFormatID = kAudioFormatLinearPCM; format->mFramesPerPacket = 1; format->mChannelsPerFrame = 1; format->mBytesPerFrame = 2; format->mBytesPerPacket = 2; format->mBitsPerChannel = 16; format->mReserved = 0; format->mFormatFlags = kLinearPCMFormatFlagIsBigEndian | kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked; }
Replies
3
Boosts
0
Views
1.5k
Activity
Feb ’23
AVPlayer pause live stream on iOS 9.3
Hi everyone!Im having difficulties trying to resume live stream playback from previously paused moment.On iOS 9.2 and below player continued to play from paused moment.On iOS 9.3 and above, when i resume playing, i receive "playerBufferEmpty" and AVPlayerItemTimeJumpedNotification, and as a result playback doesnt continue from the paused moment.This looks like an issue in AVPlayer since everything works on iOS versions 9.2 and below. I also tried playerItem.canUseNetworkResourcesForLiveStreamingWhilePaused , but it doesnt help.Are there any changes in AVPlayer/AVPlayerItem regarding this from iOS 9.2 to iOS 9.3?Thanks!
Replies
6
Boosts
0
Views
2.8k
Activity
Oct ’21
Processing / tapping an HLS audio stream (or global app output)
I'm trying to do some realtime audio processing on audio served from an HLS stream (i.e. an AVPlayer created using an M3U HTTP URL). It doesn't seem like attaching an AVAudioMix configured with with an `audioTapProcessor` has any effect; none of the callbacks except `init` are being invoked. Is this a known limitation? If so, is this documented somewhere?If the above is a limitation, what are my options using some of the other audio APIs? I looked into `AVAudioEngine` as well but it doesn't seem like there's any way I can configure any of the input node types to use an HLS stream. Am I wrong? Are there lower level APIs available to play HLS streams that provide the necessary hooks?Alternatively, is there some generic way to tap into all audio being output by my app regardless of its source?Thanks a lot!
Replies
11
Boosts
0
Views
5.1k
Activity
Sep ’23