Showing posts with label avfoundation. Show all posts
Showing posts with label avfoundation. Show all posts

Tuesday, September 11, 2018

Convert NSDate from AVDateRangeMetadataGroup to CMTime

Leave a Comment

AVPlayer primarily measures times with CMTime. However when using an AVPlayerItemMetadataCollector to collect date range metadata from an HLS stream, the resulting AVDateRangeMetadataGroups hold NSDates instead of CMTimes.

My problem is I want to add a boundary time observer to the player so I know when the playback head actually enters the date range, but you can only add a boundary time observer using CMTime. AVPlayer and AVPlayerItem can seek to a Date and can give me the current playback head as a Date, but I don't see any way to convert a given Date into a CMTime that I can use to set a boundary time observer.

In theory if I knew what the EXT-X-PROGRAM-DATE-TIME tag said I could calculate a CMTime offset myself, but I don't see a way to retrieve that.

The only other thought I had was to retrieve both currentTime and currentDate from the AVPlayerItem, then calculate the relative offset between currentDate and my target date and apply that to the CMTime. But a problem with this solution is the currentDate and currentTime won't represent the exact same time. The delta is presumably going to be very small, but it won't be zero (unless the rate itself is zero).

1 Answers

Answers 1

I hope it is the easiest solution: You can try using CMTime.init(seconds: Double, preferredTimescale: CMTimeScale) You can calculate the seconds from your NSDate objects and that way pass them into CMTime's function. This might sound trivial but hope it helps.

Also as I mentioned above to know when currentTime is not in the nil state try overriding the property and set a property observer on it and put a print statement into your override. That way you will see in the debug console whenever it will change state. You can then trace it and set brakepoints to it.

Read More

Wednesday, August 8, 2018

AVAudioSession configuration to record and play with others

Leave a Comment

I want to configure AVAudioSession that I can record video with audio and also play music from Music app (or any other app that is producing sound, typically internet radios apps)

I configure session like this:

try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, with: .mixWithOthers) try? AVAudioSession.sharedInstance().setActive(true, with: .notifyOthersOnDeactivation) 

This works the way that when my recording app is running I can start playing audio from music app and record video (also record audio as well). So far good.

Now, I put my recording app to the background. Music app continues to play. It is fine. But, when my app is coming back from background music app stop its playback. I would like it to continue. So it basically behaves as build in camera app when shooting video. Is there a way to tell the system that I want other app to continue playback?

1 Answers

Answers 1

I have almost met the similar problem and it is almost killed my one-two days for figure outing the problem.

In my case, I am used AVCaptureSession for video/audio recording and it has property called automaticallyConfiguresApplicationAudioSession. As per Apple docs

automaticallyConfiguresApplicationAudioSession: A Boolean value that indicates whether the capture session automatically changes settings in the app’s shared audio session.

The value of this property defaults to true, causing the capture session to automatically configure the app’s shared AVAudioSession instance for optimal recording

So If we are manually setting the AVAudioSession, we should set this property as false like below,

captureSession.automaticallyConfiguresApplicationAudioSession = false; 

Making this property to false and setting appropriate AVAudioSession categories manually has solved my issue! Hope it will help in your case too!

Some more Observations on your code

  • There is no need of .notifyOthersOnDeactivation flag to activating an audio session This flag is used only when deactivating your audio session. That is when you pass a value of false in the beActive parameter of the setActive(_:options:) instance method. So the below code fine for active a session try? AVAudioSession.sharedInstance().setActive(true)
  • In default the AVAudioSessionCategoryPlayAndRecord category leads to a very low volume of background sound. If you want normal volume, need to use the option .defaultToSpeaker with .mixWithOthers as follows,

    try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.mixWithOthers, .defaultToSpeaker])

Oke! then I think It will now work fine if you have done all other stuff properly.

Note** I have created a working sample project for your reference and you can found it on GitHub Here

Read More

Thursday, July 12, 2018

AVPlayerLayer in UICollectionViewCell, or how to load gifs as WhatsApp

Leave a Comment

In the app I have a UICollectionView with item size so that about ~20 items are visible on the screen at the same time. The content that I want to display in each cell is Gif image downloaded from Giphy / Tenor.

However, I realized that gif files take much more space (and time to load) than the relative mp4 files that both Tenor and Giphy provide for each animated image, which is actually obvious, cause mp4 file format has a compressing logic and stuff like that. Sorry if I use wrong terms.

In order to have list loaded faster I decided to switch using UIImageView with GIF images to AVPlayerLayer, cause mp4 file is like ~10x lighter than GIF image. But I faced with the performance issue similar to what described HERE. The flow is mostly the same, I have 20+ items visible at the same time, but because of hardware limitations it only shows 16 videos. I couldn't find any workaround or any other frameworks that would allow to have more than 16 AVPlayerLayer showing video at the same time.

I'm wondering how WhatsApp application works and handles this logic. It also has GIF selection from Tenor. I already checked and figured out that WhatsApp downloads small video files and not gif images. That's why it loads very fast. But I have no idea how they can show 20+ items at the same time. HERE is how that works in WhatsApp - https://media.giphy.com/media/33E84h3RAVn0vQWZak/giphy.gif. Also, I notices during scroll the small static previews are showing, but I don't see the app making requests for it. Probably they gets a first frame of the gif on the fly without any delays in main thread.

I also tried that, but even if I make every single stuff in background thread and the only line on the main thread is "self.imageView.image = myImage", it anyway is lugging a little bit if I have 8 items in the row for example and scrolling very fast.

I see only 2 possible solutions to have it loads fast (so we definitely need to load mp4 instead of gifs), and scroll smooth and without lugs:
1. WhatsApp uses its own custom Video Core to display video in the UICollectionViewCell .
2. WhatsApp downloads video to speed up the download process but then encodes mp4 file to gif one on the fly and use regular animated UIImageView to show the output gif file. However I was not able to have this flow working very fast without lugging during 'massive' scrolling

Any thoughts on how to implement the same to make it works fast and smooth as in WhatsApp? I'm unable to check how it handles the downloaded info, but for sure it downloads mp4 files and not gif ones.

0 Answers

Read More

Tuesday, June 12, 2018

AVMutableVideoComposition output video shrinked

Leave a Comment

I'm a newbie to Swift. I'm trying to add a watermark with reference to code from SO. My original video resolution is 1280 X 720, but the output video is a shrinked version.

Here are the before and after pictures

Before

After

Here is my function to create a watermark.

private func watermark(video videoAsset:AVAsset, watermarkText text : String!, image : CGImage!, saveToLibrary flag : Bool, completion : ((_ status : AVAssetExportSessionStatus?, _ session: AVAssetExportSession?, _ outputURL : URL?) -> ())?) {     DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {          let mixComposition = AVMutableComposition()          let compositionVideoTrack = mixComposition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))         let clipVideoTrack = videoAsset.tracks(withMediaType: AVMediaTypeVideo)[0]         do {             try compositionVideoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: clipVideoTrack, at: kCMTimeZero)         }         catch {             print(error.localizedDescription)         }          let videoSize = clipVideoTrack.naturalSize          print("Video size", videoSize.height) //720         print("Video size", videoSize.width) //1280          let parentLayer = CALayer()         let videoLayer = CALayer()         parentLayer.frame = CGRect(x: 0.0,                                    y: 0.0,                                    width: videoSize.width,                                    height: videoSize.height)         videoLayer.frame = CGRect(x: 0.0,                                   y: 0.0,                                   width: videoSize.width,                                   height: videoSize.height)         parentLayer.addSublayer(videoLayer)          if text != nil {             let titleLayer = CATextLayer()             titleLayer.backgroundColor = UIColor.red.cgColor             titleLayer.string = text             titleLayer.font = "Helvetica" as CFTypeRef             titleLayer.fontSize = 15             titleLayer.alignmentMode = kCAAlignmentCenter             titleLayer.bounds = CGRect(x: 0, y: 0, width: videoSize.width, height: videoSize.height)             parentLayer.addSublayer(titleLayer)         } else if image != nil {             let imageLayer = CALayer()             imageLayer.contents = image              let width: CGFloat = (self.imageView.image?.size.width)!             let height: CGFloat = (self.imageView.image?.size.height)!              print("Video size", height) //720             print("Video size", width) //1280              imageLayer.frame = CGRect(x: 0.0, y: 0.0, width: width, height: height)             imageLayer.opacity = 0.65             parentLayer.addSublayer(imageLayer)         }          let videoComp = AVMutableVideoComposition()         videoComp.renderSize = videoSize         videoComp.frameDuration = CMTimeMake(1, Int32(clipVideoTrack.nominalFrameRate))         videoComp.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer)          let instruction = AVMutableVideoCompositionInstruction()         instruction.timeRange = CMTimeRangeMake(kCMTimeZero, mixComposition.duration)         _ = mixComposition.tracks(withMediaType: AVMediaTypeVideo)[0] as AVAssetTrack          let layerInstruction = self.videoCompositionInstructionForTrack(track: compositionVideoTrack, asset: videoAsset)          instruction.layerInstructions = [layerInstruction]         videoComp.instructions = [instruction]          let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]         let dateFormatter = DateFormatter()         dateFormatter.dateStyle = .long         dateFormatter.timeStyle = .short         let date = dateFormatter.string(from: Date())         let url = URL(fileURLWithPath: documentDirectory).appendingPathComponent("watermarkVideo-\(date).mov")          let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)         exporter?.outputURL = url         exporter?.outputFileType = AVFileTypeQuickTimeMovie         exporter?.shouldOptimizeForNetworkUse = true         exporter?.videoComposition = videoComp          exporter?.exportAsynchronously() {             DispatchQueue.main.async {                  if exporter?.status == AVAssetExportSessionStatus.completed {                     let outputURL = exporter?.outputURL                     if flag {                          if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(outputURL!.path) {                             PHPhotoLibrary.shared().performChanges({                                 PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: outputURL!)                             }) { saved, error in                                 if saved {                                     completion!(AVAssetExportSessionStatus.completed, exporter, outputURL)                                 }                             }                         }                     } else {                         completion!(AVAssetExportSessionStatus.completed, exporter, outputURL)                     }                  } else {                     // Error                     completion!(exporter?.status, exporter, nil)                 }             }         }     } } 

While the size of watermark image is absolutely correct, the video is really shrinked.

2 Answers

Answers 1

can you try this function

private func watermark(video videoAsset: AVAsset, watermarkText text : String!, image : CGImage!, saveToLibrary flag : Bool, completion : ((_ status : AVAssetExportSessionStatus ?, _ session: AVAssetExportSession ?, _ outputURL : URL ?) -> ())?) {   DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {      let mixComposition = AVMutableComposition()      let compositionVideoTrack = mixComposition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))     let clipVideoTrack = videoAsset.tracks(withMediaType: AVMediaTypeVideo)[0] as AVAssetTrack     do {       try compositionVideoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: clipVideoTrack, at: kCMTimeZero)     }       catch {       print(error.localizedDescription)     }      let videoSize = clipVideoTrack.naturalSize      let parentLayer = CALayer()     let videoLayer = CALayer()     parentLayer.frame = CGRect(x: 0.0,       y: 0.0,       width: videoSize.width,       height: videoSize.height)     videoLayer.frame = CGRect(x: 0.0,       y: 0.0,       width: videoSize.width,       height: videoSize.height)     parentLayer.addSublayer(videoLayer)      //            if text != nil {     //                let titleLayer = CATextLayer()     //                titleLayer.backgroundColor = UIColor.red.cgColor     //                titleLayer.string = text     //                titleLayer.font = "Helvetica" as CFTypeRef     //                titleLayer.fontSize = 15     //                titleLayer.alignmentMode = kCAAlignmentCenter     //                titleLayer.frame = CGRect(x: 0, y: 0, width: videoSize.width, height: videoSize.height)     //                parentLayer.addSublayer(titleLayer)     //            } else     if image != nil {       let imageLayer = CALayer()       imageLayer.contents = image        let width: CGFloat = (self.imageView.image ?.size.width)!       let height: CGFloat = (self.imageView.image ?.size.height)!       //       print("Video size", height)       print("Video size", width)        imageLayer.frame = CGRect(x: 0, y: 0, width: width, height: height)        //                imageLayer.frame = CGRect(x: 0, y: 0, width: videoSize.width, height: videoSize.height)        imageLayer.opacity = 1       parentLayer.addSublayer(imageLayer)     }      let videoComp = AVMutableVideoComposition()     videoComp.renderSize = videoSize     videoComp.frameDuration = CMTimeMake(1, Int32(clipVideoTrack.nominalFrameRate))     videoComp.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer)      let instruction = AVMutableVideoCompositionInstruction()     instruction.timeRange = CMTimeRangeMake(kCMTimeZero, mixComposition.duration)     let videotrack = mixComposition.tracks(withMediaType: AVMediaTypeVideo)[0] as AVAssetTrack     let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videotrack)      //            let layerInstruction = self.videoCompositionInstructionForTrack(track: compositionVideoTrack, asset: videoAsset)      instruction.layerInstructions = [layerInstruction]     videoComp.instructions = [instruction]      let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]     let dateFormatter = DateFormatter()     dateFormatter.dateStyle = .long     dateFormatter.timeStyle = .short     let date = dateFormatter.string(from: Date())     let url = URL(fileURLWithPath: documentDirectory).appendingPathComponent("watermarkVideo-\(date).mp4")      guard let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality) else { return}     exporter.videoComposition = videoComp     exporter.outputFileType = AVFileTypeMPEG4     exporter.outputURL = url      exporter.exportAsynchronously() {       DispatchQueue.main.async {          if exporter.status == AVAssetExportSessionStatus.completed {           let outputURL = exporter.outputURL           if flag {             // Save to library             //                            let library = ALAssetsLibrary()              if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(outputURL!.path) {               PHPhotoLibrary.shared().performChanges({                 PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: outputURL!)               }) {                 saved, error in                               if saved {                   completion!(AVAssetExportSessionStatus.completed, exporter, outputURL)                 }               }             }              //                            if library.videoAtPathIs(compatibleWithSavedPhotosAlbum: outputURL) {             //                                library.writeVideoAtPathToSavedPhotosAlbum(outputURL,             //                                                                           completionBlock: { (assetURL:NSURL!, error:NSError!) -> Void in             //             //                                                                            completion!(AVAssetExportSessionStatus.Completed, exporter, outputURL)             //                                })             //                            }           } else {             completion!(AVAssetExportSessionStatus.completed, exporter, outputURL)           }          } else {           // Error           completion!(exporter.status, exporter, nil)         }       }     }   } } 

Answers 2

The code above for creating the watermarked video seems not to be the reason for the smaller output resolution.

Problem

The resolution depends on what kind of AVAsset is put into the watermark method.

Example: Frequently an UIImagePickerController is used. There is the delegate method

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])  

There one often can see something like this:

let url = info[UIImagePickerControllerMediaURL] as? URL let videoAsset = AVAsset(url: url!) self.watermark(video: videoAsset, watermarkText: nil, image: self.imageView.image?.cgImage ... 

But with the lines above a downsized input image is used, e.g. instead of having a video with 1920x1080 one has a reduced video size of 1280x720.

Solution

A method for determining the AVAsset from the PHAsset could look like this:

private func videoAsset(for asset: PHAsset, completion: @escaping (AVAsset?) -> Void) {     let requestOptions = PHVideoRequestOptions()     requestOptions.version = .original     PHImageManager.default().requestAVAsset(forVideo: asset, options: requestOptions, resultHandler: {         (avAsset, avAudioMix, info) in         completion(avAsset)     }) } 

And where to get the PHAsset from? It can also be determined in the didFinishPickingMediaWithInfo method by using UIImagePickerControllerPHAsset:

let asset = info[UIImagePickerControllerPHAsset] as? PHAsset 

Quick Test

For a quick test one could use:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {     if let asset = info[UIImagePickerControllerPHAsset] as? PHAsset {         picker.dismiss(animated: true, completion: { [weak self] in             self?.videoAsset(for: asset, completion: { (avAsset) in                 if let videoAsset = avAsset {                     DispatchQueue.main.async {                         self?.watermark(video: videoAsset, watermarkText: nil, image: self?.imageView.image?.cgImage, saveToLibrary: true) { (exportStat: AVAssetExportSessionStatus? , session: AVAssetExportSession?, url: URL?) in                             print("url: \(String(describing: url?.debugDescription))")                         }                     }                 }             })         })     } } 

The result is a video in the original resolution with a watermark on the lower left, see screenshot of resulting video:

test of adding watermark

Read More

Tuesday, May 22, 2018

iOS 11 AVPlayer crash when KVO

Leave a Comment

I got a weird crash when using AVPlayer to play a remote video. From the crash log on Fabric, the App crash on system thread (com.apple.avfoundation.playerlayer.configuration). The crash log is below:

Crashed: com.apple.avfoundation.playerlayer.configuration 0  libsystem_kernel.dylib         0x1839ac2e8 __pthread_kill + 8 1  libsystem_pthread.dylib        0x183ac12f8 pthread_kill$VARIANT$mp + 396 2  libsystem_c.dylib              0x18391afbc abort + 140 3  libsystem_malloc.dylib         0x1839e3ce4 szone_size + 634 4  QuartzCore                     0x187ed75e8 -[CALayer dealloc] + 72 5  QuartzCore                     0x187e75d90 CA::Transaction::commit() + 1052 6  AVFoundation                   0x18973b4a8 -[AVPlayerLayer observeValueForKeyPath:ofObject:change:context:] + 684 7  Foundation                     0x1847a2894 NSKeyValueNotifyObserver + 304 8  Foundation                     0x1847bc364 -[NSObject(NSKeyValueObserverRegistration) _addObserver:forProperty:options:context:] + 204 9  Foundation                     0x1847bc13c -[NSObject(NSKeyValueObserverRegistration) addObserver:forKeyPath:options:context:] + 124 10 AVFoundation                   0x189760714 -[AVPlayer addObserver:forKeyPath:options:context:] + 204 11 AVFoundation                   0x189890414 -[AVKVODispatcher startObservingValueAtKeyPath:ofObject:options:usingBlock:] + 136 12 AVFoundation                   0x18989189c -[AVKVODispatcher(LegacyCallbackMethod) startObservingObject:weakObserver:forKeyPath:options:context:] + 152 13 AVFoundation                   0x18973aef4 -[AVPlayerLayer _startObservingPlayer:] + 328 14 libdispatch.dylib              0x183816a54 _dispatch_call_block_and_release + 24 15 libdispatch.dylib              0x183816a14 _dispatch_client_callout + 16 16 libdispatch.dylib              0x18382096c _dispatch_queue_serial_drain$VARIANT$mp + 528 17 libdispatch.dylib              0x1838212fc _dispatch_queue_invoke$VARIANT$mp + 340 18 libdispatch.dylib              0x183821d20 _dispatch_root_queue_drain_deferred_wlh$VARIANT$mp + 404 19 libdispatch.dylib              0x18382a03c _dispatch_workloop_worker_thread$VARIANT$mp + 644 20 libsystem_pthread.dylib        0x183abef1c _pthread_wqthread + 932 21 libsystem_pthread.dylib        0x183abeb6c start_wqthread + 4 

Notice: all of crash happened on iOS11

Does anybody have idea why this crash occured?

1 Answers

Answers 1

From your stack trace, I noticed that AVPlayerLayer observeValueForKeyPath:ofObject:change:context: seems to be the cause of your issue. Hence I believe you must be implementing KVO for AVPlayer.

In which case, note two points:

  1. With the new Key-Value-Observing iOS 11 API you have relaxed requirements, however these requirements for not having to deregister from observations only apply under the following conditions:

Relaxed Key-Value Observing Unregistration Requirements

• The object must be using KVO autonotifying, rather than manually calling -will and -didChangeValueForKey: (i.e. it should not return NO from +automaticallyNotifiesObserversForKey:).

• The object must not override the (private) accessors for internal KVO state.

See here to see this being implemented in the new API with the old API addObserver and removeObserver methods. Note that the documentation is not very helpful for the new API as yet because it still is based on the old KVO implementation. But, as you can see deregistering happens automatically on deinit.

AVFoundation hides the implementation of AVPlayer for KVO support (it's a private framework), but it is likely that these relaxed requirements do not apply for AVPlayer. This code snippet from Apple in 2018, uses AVPlayer with the new KVO API, but still deregisters in a deinit method (confirming suspicions that AVPlayer does not meet the relaxed unregistration requirements for the new API).

Another explanation is that deregistering happens in deinit, but not necessarily done in the main thread. This is important for AVPlayer KVO.

  1. The reason this is important can be found from the docs:

General State Observations: You should register and unregister for KVO change notifications on the main thread. This avoids the possibility of receiving a partial notification if a change is being made on another thread.

In summary, if implementing KVO for AVPlayer with the new API, you need to explicitly unregister when you're done. Also, wrap your registering and unregistering code inside a DispatchQueue.main.async { } or similar variant.

I have assumed here that your key path is valid (just make sure they are dynamic properties).

Read More

Friday, April 27, 2018

Add video overlay (with alpha component) on another video and export it

Leave a Comment

enter image description hereI want to add overlay of video (with alpha component) on another video. I need to play and export that as well. I have tried many things ,many tutorials but i am unable to do that.

I have also tried to use FFMPEG but its to complicated to understand in short time.so i tried to use wrapper but i am unable to run that on my device. Is anyone have any idea how to do this ? NOTE : I need to export that as well.

2 Answers

Answers 1

As long as your video has been setup right to be transparent you can add the AVPlayerLayer over the other video and set this overlay video layer compositing filter to screenBlendMode.This is working for me on a current project.

overlayVideoLayer.compositingFilter = "screenBlendMode" 

Answers 2

I have try with using ffmpeg and its working

Command to Overlay

ffmpeg -y -i /videoloc/video.3gp -i /overlaylocation/Overlay.png -filter_complex [1][0]scale2ref[i][m];[m][i]overlay[v] -preset ultrafast -map [v] -map 0:a? -ac 2 /savevideolocation/file_20180427_125453.mp4

Read More

Saturday, September 30, 2017

Making video from UIImage array with different transition animations

Leave a Comment

I am following this code to create Video from an UIImage Array. While transitioning from one image to another, there is no animation here. I want to add some photo transition effect like these :

  1. TransitionFlipFromTop
  2. TransitionFlipFromBottom
  3. TransitionFlipFromLeft
  4. TransitionFlipFromRight
  5. TransitionCurlUp
  6. TransitionCurlDown
  7. TransitionCrossDissolve
  8. FadeIn
  9. FadeOut

These animations can be done via UIView.transition() & UIView.animate().

But how to apply these transition animations while making a video from an UIImage array? I have searched a lot but didn't find anything.

I've also tried HJImagesToVideo but it offers only Crossfade transition .

0 Answers

Read More

Tuesday, March 7, 2017

iOS: AVSpeechSynthesizer : need to speak text in Headphone left channel

Leave a Comment

I am using AVSpeechSynthesizer for TextToSpeech. I have to play the speak in HeadPhone left Channel (Mono 2). I have got the following to set the output channel.

func initalizeSpeechForRightChannel(){     let avSession = AVAudioSession.sharedInstance()     let route = avSession.currentRoute     let outputPorts = route.outputs     var channels:[AVAudioSessionChannelDescription] = []     //NSMutableArray *channels = [NSMutableArray array];     var leftAudioChannel:AVAudioSessionChannelDescription? = nil     var leftAudioPortDesc:AVAudioSessionPortDescription? = nil      for  outputPort in outputPorts {         for channel in outputPort.channels! {             leftAudioPortDesc = outputPort             //print("Name: \(channel.channelName)")             if channel.channelName == "Headphones Left" {                 channels.append(channel)                 leftAudioChannel = channel             }else {                // leftAudioPortDesc?.channels?.removeObject(channel)             }         }      }      if channels.count > 0 {         if #available(iOS 10.0, *) {             print("Setting Left Channel")             speechSynthesizer.outputChannels = channels             print("Checking output channel : \(speechSynthesizer.outputChannels?.count)")          } else {             // Fallback on earlier versions             }         }     } 

I have 2 problems in the code

1. Cant able to set outputchannels , It always nil (It is happening on first time calling this method, consecutive calls working fine)

2. outputchannels supports from iOS 10.* But I need to support it from iOS 8.0

Please provide the best way to do that.

1 Answers

Answers 1

  1. Instead of checking the channelName, which is descriptive (i.e. for the user), check the channelLabel. There is an enumeration containing the left channel.

  2. I suspect this may not be possible pre-iOS 10. AVAudioSession doesn't appear to have any method to select only the left output channel. You may be able to use overrideAudioPort:error but it would affect the entire app.

Read More

Saturday, June 11, 2016

AVPlayer play the video,can play a sound, but video images stuck

Leave a Comment

I go to create AVPlayerItem through AVURLAsset,This is my code:

let asset = AVURLAsset(URL: safeURL, options: [AVURLAssetPreferPreciseDurationAndTimingKey: true])     asset.loadValuesAsynchronouslyForKeys([assetKeyPlayable, self.assetKeyTracks, self.assetKeyHasProtectedContent]) {         () -> Void in         dispatch_async(dispatch_get_main_queue(), {             () -> Void in             // Use the AVAsset playable property to detect whether the asset can be played             if !asset.playable {                 let localizedDescription = "Item cannot be played,Item cannot be played description"                 let localizedFailureReason = "The assets tracks were loaded, but could not be made playable,Item cannot be played failure reason"                 let userInfo = [NSLocalizedDescriptionKey: localizedDescription, NSLocalizedFailureReasonErrorKey: localizedFailureReason]                 let error = NSError(domain: "domain", code: 0, userInfo: userInfo)                 self.videoPlayerDelegate?.videoPlayer?(self, playerItemStatusDidFail: error)                 self.cleanPlayer()                 return             }             // At this point we're ready to set up for playback of the asset. Stop observing             if let _ = self.player?.currentItem {                 self.cleanPlayer()             }             if asset.URL.absoluteString != safeURL.absoluteString {                 return             }             var error: NSError?             let status = asset.statusOfValueForKey(self.assetKeyTracks, error: &error)             var playerItem = AVPlayerItem(URL: safeURL)             if status == .Loaded {                 playerItem = AVPlayerItem(asset: asset)             } else {                 // You should deal with the error appropriately.If Loaded fails, create an AVPlayerItem directly from the URL                 playerItem = AVPlayerItem(URL: safeURL)             }             self.player = self.playerWithPlayerItem(playerItem)             self.registerMonitoring()             self.registerNotification()             self.addTimeObserver()             completionBlock?(loadURLString: playerURL.absoluteString)         })     } 

Add AVPlayerLayer display video in my View,This is my code:

// MARK: - Property

var player: AVPlayer? {     get {         return playerLayer.player     }      set {         playerLayer.player = newValue     } }  var playerLayer: AVPlayerLayer {     return layer as! AVPlayerLayer } 

When displaying video after completion of loading

self.videoPlayer?.loadPlayer({         [weak self](loadURLString) in         if let strongSelf = self {             strongSelf.player = strongSelf.videoPlayer?.player             strongSelf.startPlay()         }     }) 

Call seekToTime method to specify the play:

self.player?.currentItem?.seekToTime(CMTimeMakeWithSeconds(time, Int32(NSEC_PER_SEC)), toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero) {         [weak self] finished in         if let weakSelf = self {             if weakSelf.isPlaying {                weakSelf.videoPlayerDelegate?.videoPlayerDidplayerItemSeekToTime?(weakSelf)             }         }     } 

Some pictures of interface is stuck

enter image description here

enter image description here

The first picture, the video there is sound, but the interface is stuck

The second picture, video not picture,but have a sound

Now I have a question, when I call seekToTime method is completed, sometimes video there is sound, but the interface gets stuck,sometimes, video not picture, But not every time,I tried to callCALayer setNeedsDisplay method,to update AVPlayerLayer picture, but no effect,Therefore, I do not know with what method to know where is the problem,Hope someone can help me.

0 Answers

Read More

Monday, April 25, 2016

How to equalize stereo input and apply audio effect only to single channel on iOS?

Leave a Comment

I need to process a stereo audio file on iOS as follows:

  • Both channels should have equal intensity, ie. make the stereo appear as mono
  • Route the mono audio to both left and right channels
  • Apply effects to the audio which is output to the right channel

What I currently have is:

            +-------------------+             | AVAudioPlayerNode +------------------------+             +--------^----------+                        |                      |                                   |             +--------+---------+                +--------v---------+     File ---> AVAudioPCMBuffer |                | AVAudioMixerNode +---> Output             +--------+---------+                +--------^---------+                      |                                   |             +--------v----------+  +-------------------+ |             | AVAudioPlayerNode +--> AVAudioUnitEffect +-+             +-------------------+  +-------------------+ 

The effect is a subclass of AVAudioUnitEffect.

I'm having trouble making the stereo input appear as mono and outputting AVAudioPlayerNode to separate channels.

I tried to set the PlayerNodes' volume to 0.5 and pan to -1.0 and 1.0, but, as the input is stereo, this doesn't yield desired effects.

With AVFoundation, I figure I have at least two options: either I…

(1) equalize the channels for PlayerNodes so both PlayerNodes appear as mono — after which I could use the same logic as before: having equal volume on both PlayerNodes, other panning left and other right and applying the effect on one PlayerNode would, after MixerNode, result the effect appear only in right output channel.

(2) Keep the PlayerNodes as stereo (pan = 0.0), apply the effect only on one PlayerNode and then tell the MixerNode to use one PlayerNode's both channels as a source for the left channel and the other's channels for the right channel. I suppose then the MixerNode would effectively equalize the input channels so it would appear as the input is mono and effect can be heard only from one output channel.

The question is: is either of the aforementioned strategies possible and how? Is there another option that I've overlooked?

I'm using Swift for the project, but can cope with Objective-C.


Judging by the lack of responses and my own research, it seems to me AVFoundation might not be the way to go. The simplicity using AVFoundation is tempting, but I'm open to alternatives. Currently I'm researching MTAudioProcessingTap-classes and they might be of use. Help is still appreciated.

0 Answers

Read More

Wednesday, April 20, 2016

How to send video streaming to WOWZA server using RTSP from iOS app?

Leave a Comment

I am new in capturing video(AVFoundation) and WOWZA server.

I have checked many solutions but didn't find any tutorials or libraries on "How to work with WOWZA server using RTSP". I found one project VideoCore on GitHub but it works only on RTMP. They have suggested answer on the RTSP problem, USE live555 protocol. But i hardly understand c++ code.

My Question:

  • How do i get video stream from AVFoundation? Right now i am getting file not stream data using AVCaptureFileOutputRecordingDelegate:

captureOutput(_: didFinishRecordingToOutputFileAtURL:, fromConnections: error:)

But i need stream output data so i can send to WOWZA server.

  • How to convert video to encoded h.264 stream?
  • How to integrate live555 library to VideoCapture class for generate RTSP URL?
  • How to send that video to WOWZA using RTSP protocol?

Please, Suggest me with any library or sample code in your answer.

0 Answers

Read More

Sunday, April 17, 2016

Accessing multichannel data from MTAudioProcessingTap

Leave a Comment

I'm using MTAudioProcessingTap and Apple's sample code to process some multichannel audio, but am wondering if it supports anything more than stereo? Despite a 6-channel AVAsset used to setup the AVMutableAudioMixInputParameters, I'm still only seeing two channels of data when the tap's "prepare" callback is called:

static void prepare(MTAudioProcessingTapRef tap, CMItemCount maxFrames, const AudioStreamBasicDescription *processingFormat)

In that callback, processingFormat->mChannelsPerFrame equals 2. But where does the processingFormat get setup in the first place? Is there a way to change this to match the 6-channel asset? In other words, does the tap support multichannel data? There's not much documentation on MTAudioProcessingTap besides the sample project and the WWDC2012 video so it's a challenge tracking down the issue. Thanks for reading.

0 Answers

Read More

Sunday, April 10, 2016

Draw button on top of AVPlayer

Leave a Comment

I have to draw a label or button on top of video relay next previous , leave comment . List of video have it, once user select one item from the table,it need to play, Once player play finished, those buttons or label should come on top of video

Here is my code :

    comPlayerControl = AVPlayerViewController()              if let player = comPlayerControl {                  let videoURL: String = "http://cdnapi.kaltura.com/p/11/sp/11/playManifest/entryId/"+selectedSubmission.transcodeRefId+"/format/applehttp/protocol/http/a.m3u8"                 let playerItem = AVPlayerItem(URL: NSURL(string: videoURL)! )                 commmentPlayer = AVPlayer(playerItem: playerItem)                 player.player = commmentPlayer                 player.view.frame = videoCell.frame                 player.view.sizeToFit()                  player.showsPlaybackControls = true                 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CommentsTableViewController.playerDidFinishPlaying(_:)),                     name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)                  comPlayerControl.delegate = self                 videoCell.addSubview(player.view)             }         func playerDidFinishPlaying(note: NSNotification) {     print("Video Finished")     let DynamicView=UIView(frame: CGRectMake(100, 200, 100, 100))     DynamicView.backgroundColor=UIColor.greenColor()     DynamicView.layer.cornerRadius=25     DynamicView.layer.borderWidth=2     DynamicView.layer.zPosition = 1;     comPlayerControl.view.addSubview(DynamicView) } 

requirement like this

requirement image

3 Answers

Answers 1

You're using an AVPlayerViewController, so there's no reason to access your application's window like in Alessandro Ornano's answer. Why reinvent the wheel? Every AVPlayerViewController has a contentOverlayView property which allows you to place views between the player and the controls.

First, create a new AVPlayerItem and listen for the AVPlayerItemDidPlayToEndTimeNotification notification on that item. Load the item into your player and begin playback.

Once the item completes, the selector your specified to listen for the AVPlayerItemDidPlayToEndTimeNotification notification will be called. In that selector, access the contentOverlayView directly and add your buttons:

In some view controller or other object:

let playerVC = AVPlayerViewController()  // ...  func setupPlayer {      let playerItem = AVPlayerItem(...)     playerVC.player?.replaceCurrentItemWithPlayerItem(playerItem)     NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(VC.itemFinished), name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)     self.presentViewController(playerVC, animated: true) {          self.playerVC.player?.play()     } }  func itemFinished() {     let btn = UIButton(type: .System)     btn.addTarget(self, action: #selector(VC.buttonTapped), forControlEvents: .TouchUpInside)     self.playerVC.contentOverlayView?.addSubview(btn) }  func buttonTapped() {     print("button was tapped")     // replay/comment logic here } 

You could also subclass AVPlayerViewController and do everything inside an instance of your subclass, but Apple warns against that:

Do not subclass AVPlayerViewController. Overriding this class’s methods is unsupported and results in undefined behavior.

Answers 2

I think the best way to make the avplayer buttons is explained here: IOS 8 Video Playback using AVPlayer and AVPlayerViewController .

So , I prefeer and agree with these instructions, but if you still want to add these buttons you can try to add them to the self.window

if let app = UIApplication.sharedApplication().delegate as? AppDelegate, let window = app.window {         let myFirstButton = UIButton()         myFirstButton.setTitle("test", forState: .Normal)         window.addSubview(myFirstButton)         ... } 

Answers 3

Based on the your question and from the comment/code of Ramis i have made a sample code which you may try

As mentioned by JAL the contentOverlayView should be the best option to display the control over the video in the AVPlayerController, but as per my my sample demo the contentOverlayview don't have any user interaction for the buttons or other controls, as if you check in the 3D view of the AVPlayerController it has AVTouchIgnoringView/UIView ahead of the contentOverlayView which may be problem in user interaction of contentOverlayView

So another solution is to add the overlay view in the AVPlayerViewController

func addContentOverlayView() {      OverlayView.frame = CGRectMake(0,30,AVPlayerVC.view.bounds.width, 100)     OverlayView.hidden = true     OverlayView.backgroundColor = UIColor ( red: 0.5, green: 0.5, blue: 0.5, alpha: 0.379 )      let btnNext = UIButton(frame:CGRectMake(AVPlayerVC.view.bounds.width - 60,0,60,44))     btnNext.setTitle(">>", forState:.Normal)     btnNext.addTarget(self, action:"playNext", forControlEvents:.TouchUpInside)     //        btnNext.layer.borderColor = UIColor ( red: 0.0, green: 0.0, blue: 1.0, alpha: 0.670476140202703 ).CGColor     //        btnNext.layer.borderWidth = 1.0     OverlayView.addSubview(btnNext)      let btnReplay = UIButton(frame:CGRectMake((AVPlayerVC.view.bounds.width/2)-40,0,80,44))     btnReplay.setTitle("Replay", forState:.Normal)     btnReplay.addTarget(self, action:"replayVideo", forControlEvents:.TouchUpInside)     OverlayView.addSubview(btnReplay)      let btnPrevious = UIButton(frame:CGRectMake(0,0,80,44))     btnPrevious.setTitle("<<", forState:.Normal)     btnPrevious.addTarget(self, action:"previousVideo", forControlEvents:.TouchUpInside)     OverlayView.addSubview(btnPrevious)      let btnComment = UIButton(frame:CGRectMake((AVPlayerVC.view.bounds.width/2)-70,40,140,44))     btnComment.setTitle("Comments", forState:.Normal)     btnComment.addTarget(self, action:"openComments", forControlEvents:.TouchUpInside)     OverlayView.addSubview(btnComment)      AVPlayerVC.view.addSubview(OverlayView);  }  func playNext() {     prevItem = AVPlayerVC.player?.currentItem     OverlayView.hidden = true     commmentQueuePlayer.advanceToNextItem() }  func replayVideo() {     OverlayView.hidden = true     AVPlayerVC.player?.currentItem?.seekToTime(kCMTimeZero)     AVPlayerVC.player?.play() }  func previousVideo() {     OverlayView.hidden = true     if prevItem != AVPlayerVC.player?.currentItem {         if (commmentQueuePlayer.canInsertItem(prevItem!, afterItem:AVPlayerVC.player?.currentItem)) {             //commmentQueuePlayer.insertItem(prevItem!, afterItem:AVPlayerVC.player?.currentItem)             commmentQueuePlayer.replaceCurrentItemWithPlayerItem(prevItem)             prevItem = AVPlayerVC.player?.currentItem             replayVideo()         }     } else {         replayVideo()         //Else display alert no prev video found     } }  func stopedPlaying() {     if prevItem == nil {         prevItem = AVPlayerVC.player?.currentItem     }     OverlayView.hidden = false } 

At the initial setup we set the AVPlayerController,AVQueuePlayer etc... at that time we can add the overlay on the AVPlayerController

For the previous item there is no direct available and as per documentation the item will be remove once it's next item is played , so we have two option like replaceCurrentItemWithPlayerItem or insertItem(item: AVPlayerItem, afterItem: AVPlayerItem?)

If you need to check complete code you can check it from : https://gist.github.com/Pyrolr/debb4fca8f608b1300e099a5b3547031

Note: This is just like prototype, it is not working perfectly in all the cases but it can help you in understanding the basic functionality you wnat and you can improve/optimise based on your requirements

Read More

Friday, March 25, 2016

How to configure AVCaptureSession for high res still images and low res (video) preview?

Leave a Comment

I'd like to capture high resolution still images using AVCaptureSession. Therefore AVCaptureSession preset is set to Photo.

This is working well so far. On an iPhone 4 the final still image resolution is at its maximum of 2448x3264 pixels and the preview (video) resolution is 852x640 pixels.

Now, because the preview frames are analyzed to detect objects in the scene, I'd like to lower their resolution. How can this be done? I've tried to set AVVideoSettings with a lower width/height to AVCaptureVideoDataOutput, but this leads to the following error message:

AVCaptureVideoDataOutput setVideoSettings:] - videoSettings dictionary contains one or more unsupported (ignored) keys: (AVVideoHeightKey, AVVideoWidthKey 

So it seems this is not the right approach to configure the size of the preview frames received by AVCaptureVideoDataOutput / AVCaptureVideoDataOutputSampleBufferDelegate. Do you have any ideas how the resolution of the preview frames can be configured?

Any advise is welcome, Thank you.

2 Answers

Answers 1

If you want to specify the settings manually, you need to set activeFormat on the AVCaptureDevice. This will be implicitly set the session preset to AVCaptureSessionPresetInputPriority.

The activeFormat takes a AVCaptureDeviceFormat but you can only take one from the list of AVCaptureDevice.formats. You'll need to go through the list and find one that fits your needs. Specifically, check that highResolutionStillImageDimensions is high enough for desired still capture and formatDescription (which needs to be inspected with CMFormatDescription* functions, e.g., CMVideoFormatDescriptionGetDimensions) matches your desired preview settings.

Answers 2

To lower the size of the output of AVCaptureVideoDataOutput you can set the bitrate to be lower thus producing a small sample size.

commonly used keys for AVCaptureVideoDataOutput are:

AVVideoAverageBitRateKey AVVideoProfileLevelKey AVVideoExpectedSourceFrameRateKey AVVideoMaxKeyFrameIntervalKey 

For example:

private static let videoCompressionOptionsMedium = [AVVideoAverageBitRateKey : 1750000,                                                     AVVideoProfileLevelKey : AVVideoProfileLevelH264BaselineAutoLevel,                                                     AVVideoExpectedSourceFrameRateKey : Int(30),                                                     AVVideoMaxKeyFrameIntervalKey : Int(30)] 
Read More