最近我使用mongoLab在heroku上创建了自己的解析服务器来存储我的数据。
我的问题是我将视频保存为解析PFFile
,但是在保存后我似乎无法将其传输。
以下是我的确切步骤。
首先,我保存UIImagePicker
//Get the video URL
let videoURL = info[UIImagePickerControllerMediaURL] as? NSURL
//Create PFFile with NSData from URL
let data = NSData(contentsOfURL: videoURL!)
videoFile = PFFile(data: data!, contentType: "video/mp4")
//Save PFFile first, then save the PFUser
PFUser.currentUser()?.setObject(videoFile!, forKey: "profileVideo")
videoFile?.saveInBackgroundWithBlock({ (succeeded, error) -> Void in
print("saved video")
PFUser.currentUser()?.saveInBackgroundWithBlock({ (succeeded, error) -> Void in
if succeeded && error == nil {
print("user saved")
//Hide progress bar
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.progressBar.alpha = 0
}, completion: { (bool) -> Void in
self.progressBar.removeFromSuperview()
})
}else{
//Show error if the save failed
let message = error!.localizedDescription
let alert = UIAlertController(title: "Uploading profile picture error!", message: message, preferredStyle: UIAlertControllerStyle.Alert)
let dismiss = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(dismiss)
self.presentViewController(alert, animated: true, completion: nil)
}
})
}, progressBlock: { (progress) -> Void in
self.progressBar.setProgress(Float(progress)/100, animated: true)
})
这一切都运作良好。当我检索PFFile
并尝试流式传输视频时,问题就在于此。这是我的代码:
//Get URL from my current user
self.videoFile = PFUser.currentUser()?.objectForKey("profileVideo") as? PFFile
self.profileVideoURL = NSURL(string: (self.videoFile?.url)!)
//Create AVPlayerController
let playerController = AVPlayerViewController()
//Set AVPlayer URL to where the file is stored on the sever
let avPlayer = AVPlayer(URL: self.profileVideoURL)
playerController.player = avPlayer
//Present the playerController
self.presentViewController(playerController, animated: true, completion: { () -> Void in
playerController.player?.play()
})
当我提出playerController
时,最终会发生什么:
为什么当我尝试流式传输视频时会发生这种情况?
非常感谢任何帮助!
更新
我最近尝试使用以下代码段播放从其他数据库保存的视频:let videoURL = NSURL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
这确认了我保存PFFile
的格式是导致错误的。
必须是此行导致错误,因为"video/mp4"
可能不是正确的格式:videoFile = PFFile(data: data!, contentType: "video/mp4")
更新2
我已经获取了位于mongoLab上的.mp4文件的直接链接,发现我可以在谷歌浏览器中播放它,但不能在safari或我的iPhone上播放。
更新3
我发现这是解析api本身的一个问题,并且与代码无关,因为我的代码在使用原始解析后端(正在关闭的那个)而不是我的自定义解析服务器时工作正常。我目前没有解决方案,但它应该随着时间的推移得到修复。
答案 0 :(得分:2)
此代码适合我
let playerController = AVPlayerViewController()
self.addChildViewController(playerController)
self.view.addSubview(playerController.view)
playerController.view.frame = self.view.frame
file!.getDataInBackgroundWithBlock({
(movieData: NSData?, error: NSError?) -> Void in
if (error == nil) {
let filemanager = NSFileManager.defaultManager()
let documentsPath : AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0]
let destinationPath:NSString = documentsPath.stringByAppendingString("/file.mov")
movieData!.writeToFile ( destinationPath as String, atomically:true)
let playerItem = AVPlayerItem(asset: AVAsset(URL: NSURL(fileURLWithPath: destinationPath as String)))
let player = AVPlayer(playerItem: playerItem)
playerController.player = player
player.play()
} else {
print ("error on getting movie data \(error?.localizedDescription)")
}
})
答案 1 :(得分:0)
解析服务器似乎不支持在Safari / iOS中进行流式传输,解决方案是使用express& amp; GridStore如下,
<强>解析 - 服务器 - 例如\ node_modules \解析服务器\ lib中\路由器\ FilesRouter 强>
{
key: 'getHandler',
value: function getHandler(req, res, content) {
var config = new _Config2.default(req.params.appId);
var filesController = config.filesController;
var filename = req.params.filename;
var video = '.mp4'
var lastFourCharacters = video.substr(video.length - 4);
if (lastFourCharacters == '.mp4') {
filesController.handleVideoStream(req, res, filename).then(function (data) {
}).catch(function (err) {
console.log('404FilesRouter');
res.status(404);
res.set('Content-Type', 'text/plain');
res.end('File not found.');
});
}else{
filesController.getFileData(config, filename).then(function (data) {
res.status(200);
res.end(data);
}).catch(function (err) {
res.status(404);
res.set('Content-Type', 'text/plain');
res.end('File not found.');
});
}
}
} , ...
<强>解析 - 服务器 - 例如\ node_modules \解析服务器\ lib中\控制器\ FilesController 强>
_createClass(FilesController, [{
key: 'getFileData',
value: function getFileData(config, filename) {
return this.adapter.getFileData(filename);
}
},{
key: 'handleVideoStream',
value: function handleVideoStream(req, res, filename) {
return this.adapter.handleVideoStream(req, res, filename);
}
}, ...
<强>解析 - 服务器 - 例如\ node_modules \解析服务器\ lib中\适配器\文件\ GridStoreAdapter 强>
... , {
key: 'handleVideoStream',
value: function handleVideoStream(req, res, filename) {
return this._connect().then(function (database) {
return _mongodb.GridStore.exist(database, filename).then(function () {
var gridStore = new _mongodb.GridStore(database, filename, 'r');
gridStore.open(function(err, GridFile) {
if(!GridFile) {
res.send(404,'Not Found');
return;
}
console.log('filename');
StreamGridFile(GridFile, req, res);
});
});
})
}
}, ...
GridStore适配器底部
function StreamGridFile(GridFile, req, res) {
var buffer_size = 1024 * 1024;//1024Kb
if (req.get('Range') != null) { //was: if(req.headers['range'])
// Range request, partialle stream the file
console.log('Range Request');
var parts = req.get('Range').replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = partialstart ? parseInt(partialstart, 10) : 0;
var end = partialend ? parseInt(partialend, 10) : GridFile.length - 1;
var chunksize = (end - start) + 1;
if(chunksize == 1){
start = 0;
partialend = false;
}
if(!partialend){
if(((GridFile.length-1) - start) < (buffer_size) ){
end = GridFile.length - 1;
}else{
end = start + (buffer_size);
}
chunksize = (end - start) + 1;
}
if(start == 0 && end == 2){
chunksize = 1;
}
res.writeHead(206, {
'Cache-Control': 'no-cache',
'Content-Range': 'bytes ' + start + '-' + end + '/' + GridFile.length,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4',
});
GridFile.seek(start, function () {
// get GridFile stream
var stream = GridFile.stream(true);
var ended = false;
var bufferIdx = 0;
var bufferAvail = 0;
var range = (end - start) + 1;
var totalbyteswanted = (end - start) + 1;
var totalbyteswritten = 0;
// write to response
stream.on('data', function (buff) {
bufferAvail += buff.length;
//Ok check if we have enough to cover our range
if(bufferAvail < range) {
//Not enough bytes to satisfy our full range
if(bufferAvail > 0)
{
//Write full buffer
res.write(buff);
totalbyteswritten += buff.length;
range -= buff.length;
bufferIdx += buff.length;
bufferAvail -= buff.length;
}
}
else{
//Enough bytes to satisfy our full range!
if(bufferAvail > 0) {
var buffer = buff.slice(0,range);
res.write(buffer);
totalbyteswritten += buffer.length;
bufferIdx += range;
bufferAvail -= range;
}
}
if(totalbyteswritten >= totalbyteswanted) {
// totalbytes = 0;
GridFile.close();
res.end();
this.destroy();
}
});
});
}else{
// res.end(GridFile);
// stream back whole file
res.header('Cache-Control', 'no-cache');
res.header('Connection', 'keep-alive');
res.header("Accept-Ranges", "bytes");
res.header('Content-Type', 'video/mp4');
res.header('Content-Length', GridFile.length);
var stream = GridFile.stream(true).pipe(res);
}
};
P.S 最初的答案由@Bragegs在这里给出 - https://github.com/ParsePlatform/parse-server/issues/1440#issuecomment-212815625。用户@ Stav1也在这个帖子中提到过它,但遗憾的是他被低估了?
答案 2 :(得分:0)
对于那些在这里停留的人来说,在查看新的Parse-Server示例更新时,Parse-server现在可以识别流媒体;但是,您应该使用Parse iOS sdk方法来检索视频。如果您要推出自定义解析服务器,则服务器代码如下所示。我按照一些流媒体方法的列表进行操作。
在以下位置找到服务器代码更改:
<强>解析 - 服务器 - 例如\ node_modules \解析服务器\ lib中\路由器\ FilesRouter 强>
{
key: 'getHandler',
value: function getHandler(req, res) {
var config = new _Config2.default(req.params.appId);
var filesController = config.filesController;
var filename = req.params.filename;
var contentType = _mime2.default.lookup(filename);
if (isFileStreamable(req, filesController)) {
filesController.getFileStream(config, filename).then(function (stream) {
handleFileStream(stream, req, res, contentType);
}).catch(function () {
res.status(404);
res.set('Content-Type', 'text/plain');
res.end('File not found.');
});
} else {
filesController.getFileData(config, filename).then(function (data) {
res.status(200);
res.set('Content-Type', contentType);
res.set('Content-Length', data.length);
res.end(data);
}).catch(function () {
res.status(404);
res.set('Content-Type', 'text/plain');
res.end('File not found.');
});
}
}},
使用iOS解析sdk(swift)进行流式传输的方法示例:
vidObject.video.getDataStreamInBackground(block: <#T##PFDataStreamResultBlock?##PFDataStreamResultBlock?##(InputStream?, Error?) -> Void#>)
答案 3 :(得分:-1)
我有一个带有parse-server的本地mongodb,需要它才能使它工作:
Parse-server stream video to IOS from PFFile.url
不知道它与非本地数据库是否相同。