如何在ios中显示和播放捕获的照片、视频和音频
大家好,我是Ios初学者,在我的项目中,我为用户提供了从相机捕获照片、视频和音频的功能,我将他们的“路径”存储在数组列表中,并将它们显示在一个表列表中,因此一切都正常 但这里我的主要要求是当我点击表格列表行,然后如果有图像文件,它必须显示或如果有视频,它必须播放音频也必须像视频一样播放我在这里写了一些代码照片和视频播放很好,但音频文件给问题我在这里做了什么错误 我的代码:-如何在ios中显示和播放捕获的照片、视频和音频,ios,objective-c,Ios,Objective C,大家好,我是Ios初学者,在我的项目中,我为用户提供了从相机捕获照片、视频和音频的功能,我将他们的“路径”存储在数组列表中,并将它们显示在一个表列表中,因此一切都正常 但这里我的主要要求是当我点击表格列表行,然后如果有图像文件,它必须显示或如果有视频,它必须播放音频也必须像视频一样播放我在这里写了一些代码照片和视频播放很好,但音频文件给问题我在这里做了什么错误 我的代码:- #导入“ViewController2.h” #进口 #进口 #进口 @界面ViewController2() { NSM
#导入“ViewController2.h”
#进口
#进口
#进口
@界面ViewController2()
{
NSMutableArray*arr_mediaType;
UIImagePickerController*图像选择器;
UIImage*快照;
NSData*data1;
NSMUTABLEARRY*arr_介质;
MPMoviePlayerController*电影播放器;
UIImageView*点;
音频录像机*\u录音机;
AVAudioPlayer*播放器;
}
@结束
@实现视图控制器2
@综合主表;
-(无效)viewDidLoad{
arr_mediaType=[[NSMutableArray alloc]init];
arr_media=[[NSMutableArray alloc]init];
maintablelist.delegate=self;
maintablelist.dataSource=self;
[超级视图下载];
}
-(iAction)拍照:(id)发送者{
imagePicker=[[UIImagePickerController alloc]init];
imagePicker.delegate=self;
imagePicker.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
imagePicker.mediaTypes=[[NSArray alloc]initWithObjects:(NSString*)kUTTypeImage,nil];
[self-presentViewController:imagePicker已设置动画:未完成:无];
}
-(iAction)录制视频:(id)发件人{
NSString*模型=[[UIDevice currentDevice]模型];
如果([model IsequalString:@“iPhone模拟器”]| |[model IsequalString:@“iPad模拟器”])
{
UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@“生气!!!”消息:@“找不到摄像头!”代理:无取消按钮:@“确定”其他按钮:无];
[警报显示];
}
其他的
{
imagePicker=[[UIImagePickerController alloc]init];
imagePicker.delegate=self;
imagePicker.videoMaximumDuration=10;
imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes=[[NSArray alloc]initWithObjects:(NSString*)kUTTypeMovie,nil];
[self-presentViewController:imagePicker已设置动画:未完成:无];
}
}
-(iAction)takeAudio:(id)发送方{
NSArray*dirpath;
NSString*docsDir;
dirpath=NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,NSUserDomainMask,是);
docsDir=dirpath[0];
NSString*文件名=[[NSProcessInfo processInfo]globallyUniqueString];//获取唯一名称
NSString*soundfile=[NSString stringWithFormat:@“sound%@.m4a”,文件名];
NSString*声音文件路径=[docsDir
stringByAppendingPathComponent:soundfile];
NSURL*soundFileURL=[NSURL fileURLWithPath:soundFilePath];
NSLog(@“文件路径:%@”,声音文件URL);
NSMutableDictionary*记录设置=[[NSMutableDictionary alloc]init];
[recordSetting setValue:[NSNumber NumberWiint:kAudioFormatMPEG4AAC]forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0]forKey:AVSampleRateKey];
[记录设置设置值:[NSNumber numberWithInt:2]forKey:AVNumberOfChannelsKey];
n错误*错误=nil;
AVAudioSession*audioSession=[AVAudioSession sharedInstance];
[音频会话设置类别:音频会话类别播放和记录
错误:无];
_录音机=[[AVAudioRecorder alloc]
initWithURL:soundFileURL
设置:记录设置
错误:&错误];
如果(错误)
{
NSLog(@“错误:%@,[error localizedDescription]);
}
否则{
NSLog(@“正常”);
[arr_media addObject:soundFilePath];
[录音机记录];
[主表列表重新加载数据];
}
}
-(void)imagePickerController:(UIImagePickerController*)picker未使用信息完成PickingMediaWithInfo:(NSDictionary*)信息{
NSString*mediaType=[info objectForKey:UIImagePickerControllerMediaType];
if([mediaType IsequalString:@“public.image”]){
[mediaType isEqual:@“照片”];
[arr_mediaType addObject:@“照片”];
snap=(UIImage*)[info-objectForKey:UIImagePickerControllerOriginalImage];
NSArray*Path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,是);
NSString*文件名=[[NSProcessInfo processInfo]globallyUniqueString];
NSString*filePath=[[paths objectAtIndex:0]stringByAppendingPathComponent:[NSString stringWithFormat:@“Pic-%@.png”,文件名]];
NSData*data=UIImageJPEG表示法(snap,1.0);
[数据写入文件:文件路径原子:是];
[picker DismissionViewControllerInitiated:是完成:无];
NSLog(@“所以最后的路径是%@”,filePath);
[arr_media addObject:filePath];
[主表列表重新加载数据];
}
否则{
[mediaType isEqual:@“视频”];
[arr_mediaType addObject:@“Video”];
NSURL*videoURL=[info-objectForKey:UIImagePickerControllerMediaURL];
NSLog(@“videoURL-->%@”,videoURL);
NSData*videoData=[NSData DATA with contents sofURL:videoURL];
NSArray*Path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,是);
NSString*文件名=[[NSProcessInfo processInfo]globallyUniqueString];
NSString*filePath=[[paths objectAtIndex:0]stringByAppendingPathComponent:[NSString stringWithFormat:@“video%@.mov”,fileName]];
BOOL success=[videoData writeToFile:filePath原子:否];
[arr_media addObject:filePath];
NSLog(@“videoURLPath-->%@”,filePath);
[picker DismissionViewController激活:是完成:ni
#import "ViewController2.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController2 ()
{
NSMutableArray * arr_mediaType;
UIImagePickerController *imagePicker;
UIImage *snap;
NSData *data1;
NSMutableArray * arr_media;
MPMoviePlayerController * moviePlayer;
UIImageView *dot;
AVAudioRecorder * _audioRecorder;
AVAudioPlayer * player;
}
@end
@implementation ViewController2
@synthesize maintablelist;
- (void)viewDidLoad {
arr_mediaType = [[NSMutableArray alloc]init];
arr_media = [[NSMutableArray alloc]init];
maintablelist.delegate = self;
maintablelist.dataSource = self;
[super viewDidLoad];
}
- (IBAction)takePicture:(id)sender {
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
- (IBAction)takeVideo:(id)sender {
NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:@"iPhone Simulator"] || [model isEqualToString:@"iPad Simulator"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Angry!!!" message:@"No Camera found!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
}
else
{
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.videoMaximumDuration = 10;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
}
- (IBAction)takeAudio:(id)sender {
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString]; // to get unique name
NSString *soundfile = [NSString stringWithFormat:@"sound%@.m4a",fileName];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:soundfile];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(@"FilePath:%@",soundFileURL);
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
NSError *error = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
error:nil];
_audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSetting
error:&error];
if (error)
{
NSLog(@"error: %@", [error localizedDescription]);
}
else {
NSLog(@"ok");
[arr_media addObject:soundFilePath];
[_audioRecorder record];
[maintablelist reloadData];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:@"public.image"]){
[mediaType isEqual: @"Photos"];
[arr_mediaType addObject:@"Photos"];
snap = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"Pic-%@.png", fileName]];
NSData *data = UIImageJPEGRepresentation(snap, 1.0);
[data writeToFile:filePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:nil];
NSLog(@"So finally path is%@",filePath);
[arr_media addObject:filePath];
[maintablelist reloadData];
}
else {
[mediaType isEqual: @"Videos"];
[arr_mediaType addObject:@"Video"];
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(@"videoURL --->>> %@",videoURL);
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"video%@.mov", fileName]];
BOOL success = [videoData writeToFile:filePath atomically:NO];
[arr_media addObject:filePath];
NSLog(@"videoURLPath --->>> %@",filePath);
[picker dismissViewControllerAnimated:YES completion:nil];
[maintablelist reloadData];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arr_mediaType.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cells=@"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:nil];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cells];
}
cell.textLabel.text = [arr_media objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:@"Photos"]) {
[moviePlayer.view removeFromSuperview];
dot =[[UIImageView alloc] initWithFrame:CGRectMake(40,320,240,128)];
dot.image = [UIImage imageNamed:[arr_media objectAtIndex:indexPath.row]];
[self.view addSubview:dot];
}
else if([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:@"Videos"])
{
[dot removeFromSuperview];
NSURL*theurl=[NSURL fileURLWithPath:[arr_media objectAtIndex:indexPath.row]];
moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:theurl];
[moviePlayer.view setFrame:CGRectMake(40, 320, 240, 128)];
[moviePlayer prepareToPlay];
[moviePlayer setShouldAutoplay:NO];
[self.view addSubview:moviePlayer.view];
}
else
{
NSString *filePath = [arr_media objectAtIndex:indexPath.row];
NSData *soundData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:filePath]];
player = [[AVAudioPlayer alloc] initWithData:soundData error:nil];
[player setDelegate:self];
[player play];
}
}
@end
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, @“image1.png”];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(image, 1);
[imageData writeToFile: filePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:^{
// Save your model data and reload table here
}];
}
}
#import "ViewController.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <MediaPlayer/MediaPlayer.h>
@interface ViewController ()
{
NSMutableArray * arr_mediaType;
UIImagePickerController *imagePicker;
UIImage *snap;
NSData *data1;
NSMutableArray * arr_media;
MPMoviePlayerController * moviePlayer;
UIImageView *dot;
}
@end
@implementation ViewController
@synthesize tbl;
- (void)viewDidLoad {
arr_mediaType = [[NSMutableArray alloc]init];
arr_media = [[NSMutableArray alloc]init];
tbl.delegate = self;
tbl.dataSource = self;
[super viewDidLoad];
}
- (IBAction)takePicture:(id)sender {
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
- (IBAction)takeVideo:(id)sender {
NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:@"iPhone Simulator"] || [model isEqualToString:@"iPad Simulator"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Angry!!!" message:@"No Camera found!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
}
else
{
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.videoMaximumDuration = 10;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
}
-(IBAction)takeAudio
{
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString]; // to get unique name
NSString *soundfile = [NSString stringWithFormat:@"sound%@.m4a",fileName];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:soundfile];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(@"FilePath:%@",soundFileURL);
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
NSError *error = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
error:nil];
_audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
if (error)
{
NSLog(@"error: %@", [error localizedDescription]);
} else {
[arr_media addObject:soundFilePath];
[_audioRecorder record];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:@"public.image"]){
[mediaType isEqual: @"Photos"];
[arr_mediaType addObject:@"Photos"];
snap = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"Pic-%@.png", fileName]];
NSData *data = UIImageJPEGRepresentation(snap, 1.0);
[data writeToFile:filePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:nil];
//UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//
// NSString *Dir = [paths objectAtIndex:0];
// NSString *fileName = [NSString stringWithFormat:@"Pic-%lf.png", [[NSDate date] timeIntervalSince1970]];
//
// //this path if you want save reference path in sqlite
// NSString *pngPath = [NSString stringWithFormat:@"%@/%@",Dir,fileName];
//
NSLog(@"So finally path is%@",filePath);
[arr_media addObject:filePath];
[tbl reloadData];
}
else {
[mediaType isEqual: @"Videos"];
[arr_mediaType addObject:@"Video"];
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(@"videoURL --->>> %@",videoURL);
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"video%@.mov", fileName]];
BOOL success = [videoData writeToFile:filePath atomically:NO];
[arr_media addObject:filePath];
NSLog(@"videoURLPath --->>> %@",filePath);
[picker dismissViewControllerAnimated:YES completion:nil];
[tbl reloadData];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arr_mediaType.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cells=@"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:nil];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cells];
}
cell.textLabel.text = [arr_media objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:@"Photos"]) {
[moviePlayer.view removeFromSuperview];
dot =[[UIImageView alloc] initWithFrame:CGRectMake(40,320,240,128)];
dot.image = [UIImage imageNamed:[arr_media objectAtIndex:indexPath.row]];
[self.view addSubview:dot];
}
else if([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:@"Videos"])
{
[dot removeFromSuperview];
// NSString*thePath=[[NSBundle mainBundle] pathForResource:[arr_media objectAtIndex:indexPath.row] ofType:@"MOV"];
NSURL*theurl=[NSURL fileURLWithPath:[arr_media objectAtIndex:indexPath.row]];
moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:theurl];
[moviePlayer.view setFrame:CGRectMake(40, 320, 240, 128)];
[moviePlayer prepareToPlay];
[moviePlayer setShouldAutoplay:NO];
[self.view addSubview:moviePlayer.view];
}
else
{
NSString *filePath = [arr_media objectAtIndex:indexPath.row];
NSData *soundData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:filePath]];
player = [[AVAudioPlayer alloc] initWithData:soundData error:nil];
[player setDelegate:self];
[player play];
}
@end