ios


how to trim a video in swift for a particular time


I am working on a task in which i have to trim the recorded video from particular start point to particular end point as entered or selected by user.
How should i suppose to do that. As i used UIVideoEditorController before but i don,t want to use the default view and i want to trim the video directly.
let FinalUrlTosave = NSURL(string: "\(newURL)")
exportSession!.outputURL=FinalUrlTosave
exportSession!.shouldOptimizeForNetworkUse = true
// exportSession.outputFileType = AVFileTypeQuickTimeMovie
exportSession!.outputFileType = AVFileTypeQuickTimeMovie;
let start:CMTime
let duration:CMTime
var st = starttime.doubleValue
var ed = endTime.doubleValue
start = CMTimeMakeWithSeconds(st, 600)
duration = CMTimeMakeWithSeconds(ed, 600)
// let timeRangeForCurrentSlice = CMTimeRangeMake(start, duration)
let range = CMTimeRangeMake(start, duration);
exportSession!.timeRange = range
exportSession!.exportAsynchronouslyWithCompletionHandler({
switch exportSession!.status{
case AVAssetExportSessionStatus.Failed:
print("failed \(exportSession!.error)")
case AVAssetExportSessionStatus.Cancelled:
print("cancelled \(exportSession!.error)")
default:
print("complete....complete")
// self.SaveVideoToPhotoLibrary(destinationURL1!)
}
})
i am trying to achieve my goal using this but not succeeding.
error message:- failed Optional(Error Domain=NSURLErrorDomain Code=-1100 "The requested URL was not found on this server." UserInfo={NSErrorFailingURLStringKey=file:///var/mobile/Containers/Data/Application/E68D3BFD-6923-4EA6-9FB3-C020CE4AA9D4/Documents/moment/jGq_9AUFa47s2ZiiPP4x.mp4, NSErrorFailingURLKey=file:///var/mobile/Containers/Data/Application/E68D3BFD-6923-4EA6-9FB3-C020CE4AA9D4/Documents/moment/jGq_9AUFa47s2ZiiPP4x.mp4, NSLocalizedDescription=The requested URL was not found on this server., NSUnderlyingError=0x1553c220 {Error Domain=N
Error occured second time :- failed Optional(Error Domain=NSURLErrorDomain Code=-3000 "Cannot create file" UserInfo={NSUnderlyingError=0x14e00000 {Error Domain=NSOSStatusErrorDomain Code=-12124 "(null)"}, NSLocalizedDescription=Cannot create file})
I found my solution using this method and it works like a charm....
func cropVideo(sourceURL1: NSURL, statTime:Float, endTime:Float)
{
let manager = NSFileManager.defaultManager()
guard let documentDirectory = try? manager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) else {return}
guard let mediaType = "mp4" as? String else {return}
guard let url = sourceURL1 as? NSURL else {return}
if mediaType == kUTTypeMovie as String || mediaType == "mp4" as String {
let asset = AVAsset(URL: url)
let length = Float(asset.duration.value) / Float(asset.duration.timescale)
print("video length: \(length) seconds")
let start = statTime
let end = endTime
var outputURL = documentDirectory.URLByAppendingPathComponent("output")
do {
try manager.createDirectoryAtURL(outputURL, withIntermediateDirectories: true, attributes: nil)
let name = Moment.newName()
outputURL = outputURL.URLByAppendingPathComponent("\(name).mp4")
}catch let error {
print(error)
}
//Remove existing file
_ = try? manager.removeItemAtURL(outputURL)
guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality) else {return}
exportSession.outputURL = outputURL
exportSession.outputFileType = AVFileTypeMPEG4
let startTime = CMTime(seconds: Double(start ?? 0), preferredTimescale: 1000)
let endTime = CMTime(seconds: Double(end ?? length), preferredTimescale: 1000)
let timeRange = CMTimeRange(start: startTime, end: endTime)
exportSession.timeRange = timeRange
exportSession.exportAsynchronouslyWithCompletionHandler{
switch exportSession.status {
case .Completed:
print("exported at \(outputURL)")
self.saveVideoTimeline(outputURL)
case .Failed:
print("failed \(exportSession.error)")
case .Cancelled:
print("cancelled \(exportSession.error)")
default: break
}
}
}
}

Related Links

How to send images and videos to server using ASHTTPRequest in ios
how to rearrange array using objective c?
swift - Twitter login button created with no completion block?
AVAnimator Assertion failure in -[AVMvidFrameDecoder advanceToFrame:] 'framebuffer num bytes'
Instagram InstagramCaption not working
Delete sections without scroll down
Facebook Login Button Throws An Error And Says I Cannot Login
In-app purchase receipt validation, “in_app” field empty
How can we pass the parameters along with block methods in objecitve-c
Apple Remote Push Notifications
Game stops working when restart button clicked
Swift - Create a custom push segue
how to set alpha on Backgroung image using Swift
Livecode revdberr invalid database connection
How to sort an array which contains objects with chars and decimals? [duplicate]
Set the selected Cell without pushing to new viewController

Categories

HOME
azure
validation
ssl
codenameone
coffeescript
blogs
player-swift
hadoop2
square-connect
smartsheet-c#-sdk-v2
eigen3
gitlab-ci-runner
rtp
co
microphone
wso2cep
epicorerp
abstract-syntax-tree
intersystems
stylesheet
iar
masstransit
opensuse
complex-networks
ollydbg
stackexchange.exceptional
nib
jackrabbit
executorservice
bits
disqus
spring-saml
runc
polymer-cli
quicksand
xargs
qmenubar
rtems
msysgit
maven-jetty-plugin
openwebanalytics
okular
laravel-routing
fasta
waf
tachyon
mailcore2
ipopt
printscreen
sqlfiddle
hyperterm
scrutinizer
jongo
viewengine
training-data
illegalstateexception
egl
actioncable
par
post-processor
hjson
nbug
selectsinglenode
scalariform
size-t
horizontalscrollview
mysql5
culture
opensc
imaging
private-methods
clearcase-remote-client
syndication-feed
short
bson
xcode6.1.1
yourls
floating-point-conversion
couchpotato
flexpaper
google-goggles
icon-fonts
square-cube
vote
google-website-optimizer
xml-dtd
c++builder-xe2
objcopy
openfeint
regexbuddy
keylogger
custom-protocol
scramble
contracts
sqlitemanager
resharper-4.5
nhaml

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App