I want to play audio file while recording with camera. I used AVAudioPlayer for playing audio and AVCamCaptureManager for recording.
But when audio starts to play, preview screen is freezing. What should i do?
Thanks for your helping. Here is the code. (I'm working on AVCam example.)
This is preview part.
if ([self captureManager] == nil) {
AVCamCaptureManager *manager = [[AVCamCaptureManager alloc] init];
[self setCaptureManager:manager];
[[self captureManager] setDelegate:self];
if ([[self captureManager] setupSession]) {
AVCaptureVideoPreviewLayer *newCaptureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:[[self captureManager] session]];
UIView *view = [self videoPreviewView];
CALayer *viewLayer = [view layer];
[viewLayer setMasksToBounds:YES];
CGRect bounds = CGRectMake(0, 0, 480, 320);
[newCaptureVideoPreviewLayer setFrame:bounds];
if ([newCaptureVideoPreviewLayer isOrientationSupported]) {
[newCaptureVideoPreviewLayer setOrientation:[DeviceProperties setPreviewOrientation]];
}
[newCaptureVideoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[viewLayer insertSublayer:newCaptureVideoPreviewLayer below:[[viewLayer sublayers] objectAtIndex:0]];
[self setCaptureVideoPreviewLayer:newCaptureVideoPreviewLayer];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[[[self captureManager] session] startRunning];
});
[self updateButtonStates];
}
And this is audio play part.
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"%#", sound] ofType:#"wav"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[audioPlayer play];
If I use AudioServicesPlaySystemSound normal without freezing but this time it only works on viewDidLoad.
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileRef;
soundFileRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) CFBridgingRetain(#"sound"), CFSTR ("wav"), NULL);
UInt32 soundID;
AudioServicesCreateSystemSoundID(soundFileRef, &soundID);
AudioServicesPlaySystemSound(soundID);
My problem wasn't for video but it was for playing a sound while in a call (voip type application) and the answer to this question worked for me:
Using vibrate and AVCaptureSession at the same time
Hope setting AVAudioSession category to AVAudioSessionCategoryPlayAndRecord will solve the problem. And also set its category options to AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionMixWithOthers. Please check the below set of code
#property (strong, nonatomic) AVAudioPlayer *audioPlayer;
NSURL *soundUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"VoicemailSound" ofType:#"mp3"]]; //Download and add a system sound to your project and mention its name and type here
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionMixWithOthers error: nil];
[self.audioPlayer prepareToPlay];
[self.audioPlayer play];
Related
I am Playing Audio from URL given below
"http://sumeetmusiclocal.wsisites.net/Songs/Kashyala Lavato (Lavani).mp3"
By Using Code given below
NSString *urlString = #"http://sumeetmusiclocal.wsisites.net/Songs/Kashyala Lavato (Lavani).mp3";
NSURL *audioFileLocationURL = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];
[audioPlayer setNumberOfLoops:-1];
if (error) {
NSLog(#"%#", [error localizedDescription]);
[[self volumeControl] setEnabled:NO];
[[self playPauseButton] setEnabled:NO];
[[self alertLabel] setText:#"Unable to load file"];
[[self alertLabel] setHidden:NO];
} else {
[[self alertLabel] setText:[NSString stringWithFormat:#"%# has loaded", #"HeadspinLong.caf"]];
[[self alertLabel] setHidden:NO];
//Make sure the system follows our playback status
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
//Load the audio into memory
[audioPlayer prepareToPlay];
}
But I getting Error saying
Printing description of error:
Error Domain=NSOSStatusErrorDomain Code=2003334207 "(null)"
2016-03-08 12:43:45.835 SumeetApp[1839:78581] The operation couldn’t be completed. (OSStatus error 2003334207.)
Can anyone please help me to solve this error or suggest me some other way for playing audio from url.
Thank you
Try This
AVURLAsset *asset = [AVURLAsset assetWithURL:[NSURL URLWithString:#"http://clips.vorwaerts-gmbh.de/VfE_html5.mp4"]];
AVPlayerItem *playerItem1 = [AVPlayerItem playerItemWithAsset:asset];
AVPlayer *player1 = [AVPlayer playerWithPlayerItem:playerItem1];
AVPlayerLayer *playerLayer1 = [AVPlayerLayer playerLayerWithPlayer:player1];
playerLayer1.videoGravity = AVLayerVideoGravityResizeAspectFill;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
playerLayer1.frame = self.view.frame;
});
[self.view.layer insertSublayer:playerLayer1 atIndex:1];
[player1 play];
Hope this work for you.
AVPlayer *player = [[AVPlayer alloc]initWithURL:[NSURL URLWithString:#"http://sumeetmusiclocal.wsisites.net/Songs/Kashyala Lavato (Lavani).mp3"]];
[player play];
Try this code this is working for me.
Try This
NSURL *url = [NSURL URLWithString:#"YOUR_MP3URL"];
self.playerItem = [AVPlayerItem playerItemWithURL:url];
self.player = [AVPlayer playerWithPlayerItem:playerItem];
self.player = [AVPlayer playerWithURL:#"YOUR_MP3URL"];
for play
[self.player play];
Hope this helps.
For Error:
you trying to access a file that didn't exist.
so, initWithContentsOfURL:audioFileLocationURL will return nil.
To play Audio:
NSURL *url = [NSURL URLWithString:#"<URL>];
self.playerItem = [AVPlayerItem playerItemWithURL:url];
self.player = [AVPlayer playerWithPlayerItem:playerItem];
self.player = [AVPlayer playerWithURL:<URL>];
[player play];
I use AVCaptureMovieFileOutput to capture a video file.
- (void)takeVideoAction:(id)sender {
NSString *outputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"output.mp4"];
NSFileManager *manager = [[NSFileManager alloc] init];
if ([manager fileExistsAtPath:outputPath]){
[manager removeItemAtPath:outputPath error:nil];
}
[movieFileOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:outputPath] recordingDelegate:self];
}
And then attempt to play it with AVPlayer, but nothing happens. From what Ive been reading, I think I need to wait for the file to finish loading in the below method instead of trying to play it right away.
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error{
AVAsset *asset = [AVAsset assetWithURL:outputFileURL];
self.playerItem = [[AVPlayerItem alloc]initWithAsset:asset];
self.player = [[AVPlayer alloc] initWithPlayerItem:self.playerItem];
self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
[[[self view] layer] insertSublayer:self.playerLayer atIndex:(int)self.view.layer.sublayers.count];
[self.playerLayer setFrame:self.view.frame];
//self.playerLayer.backgroundColor = [UIColor yellowColor].CGColor;
[self.player play];
}
When I remove the line :
NSFileManager *manager = [[NSFileManager alloc] init];
if ([manager fileExistsAtPath:outputPath]){
[manager removeItemAtPath:outputPath error:nil];
}
it works.
For some reason, the cleanupPlayer method is a little buggy and isn't releasing the audio player correctly. My application crashes from time to time, and I suspect it's due to a memory issue. Also, when I try to play an audio file twice (on button click), the second time the audio sometimes cuts out. I'm a bit of a newbie, so any help would be greatly appreciated!
Here is a snippet of code:
.h file:
#property (retain,nonatomic)AVAudioPlayer *player;
.m file:
-(void)playSound:(NSString *)fileName
{
// Play
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:kSoundFileType]];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
_player.delegate = self;
[_player prepareToPlay];
[_player play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[self cleanupPlayer];
}
-(void)cleanupPlayer
{
if(_player != nil) {
[_player release];
}
try this...
-(void)playSound:(NSString *)fileName
{
if (_player.isPlaying) {
[_player stop];
}
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:#"mp3"]];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
_player.delegate = self;
[_player prepareToPlay];
[_player play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[self cleanupPlayer];
}
-(void)cleanupPlayer
{
_player =nil;
}
Its simple: My video player shows up, but never plays anything. The file I am trying to play exist already (checked).
I am just starting with a new "Single View" project.
#import "ViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#interface ViewController ()
#property (nonatomic, strong) MPMoviePlayerController *player;
#end
#implementation ViewController
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filepath = [NSString stringWithFormat:#"%#/Videos/fileSequence0.ts", documentsDirectory];
NSLog(#"!! %i", [[NSFileManager defaultManager] fileExistsAtPath:filepath]);
NSURL *fileURL = [NSURL fileURLWithPath:filepath];
_player = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
[_player.view setFrame: CGRectMake(0, 0, 500, 500)];
[self.view addSubview:_player.view];
[_player play];
}
#end
Use below written code just before executing play statement.
_player.numberOfLoops=0;
_player.delegate=self;
[_player prepareToPlay];
.ts extension not works with ios. try some other extension videos ie. .mp4 . if problem arises then try to use [_player prepareToPlay];
try this one- Convert your url into NSdata
NSString* resourcePath = self.audioStr; //your video file formet should be .mp4
NSData *_objectData = [NSData dataWithContentsOfURL:[NSURL URLWithString:resourcePath]];
NSError *error = [[NSError alloc] init];
NSLog(#"url is %#",resourcePath);
_player = [[MPMoviePlayerController alloc] initWithData:_objectData error:&error];
[_player.view setFrame: CGRectMake(0, 0, 500, 500)];
[_player prepareToPlay];
_player.controlStyle = MPMovieControlStyleFullscreen;
_player.shouldAutoplay = NO;
[_player setFullscreen:YES animated:YES];
[self.view addSubview:_player.view];
[_player play];
hope it will help u
sorry for my question but i´ve implemented a intro- video and despite of the hardware silent-switch of my iPad, the audio is playing.
I´m also using the AVAudioplayer within my app just for playing short sound samples. Within this class, its the only region where i´ve set up the "AVAudioSessionCategory".
But for all audio playback only, there´s nothing hearable. Its just for my intro-video.
Any help how to fix that "audio-bug" so the movie player is silent?
Thanks you
Here´s my Audio-class:
- (id)initWithSoundfileName:(NSString*) file
{
if ((self = [super init]))
{
NSString* filename = [file stringByDeletingPathExtension];
NSString* fileextension = [file pathExtension];
// get file path from bundle
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: filename ofType: fileextension];
NSLog(#"AudioPlayer init: %#", soundFilePath);
NSURL* fileurl = [[NSURL alloc] initFileURLWithPath:soundFilePath];
NSError* error = nil;
AVAudioPlayer* audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileurl error:&error ];
if (error) { NSLog(#"Error creating AVAudioPlayer %#", [error description]);}
// set audio policy
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:NULL];
self.player = audioplayer;
[self.player prepareToPlay];
[self.player setDelegate:self];
}
return self;
}
-(void) play{
[self.player play];
}
And here´s my video-playback method:
- (void)playIntroVideo
{
NSString *movpath = [[NSBundle mainBundle] pathForResource:#"mymovie" ofType:#"mp4"];
NSURL *fileURL = [NSURL fileURLWithPath:movpath];
self.moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
self.moviePlayerController.fullscreen = YES;
self.moviePlayerController.scalingMode = MPMovieScalingModeAspectFit;
self.moviePlayerController.controlStyle = MPMovieControlStyleNone;
self.moviePlayerController.movieSourceType = MPMovieSourceTypeFile;
self.moviePlayerController.useApplicationAudioSession = NO;
[self.moviePlayerController.view setFrame: self.view.bounds];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(moviePlayBackComplete:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:self.moviePlayerController];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(moviePlaybackStateChanged:)
name:MPMoviePlayerPlaybackStateDidChangeNotification
object:self.moviePlayerController];
[self.view addSubview:self.moviePlayerController.view];
[self.moviePlayerController prepareToPlay];
[self.moviePlayerController play];
}
Like #Till mentioned:
When I change the MoviePlayerController property to useApplicationAudioSession=TRUE, it fixes my problem. Audio Playback is silent.