What is the most correct way to add a sound to a UIAlertView?
Should I subclass it and then play a system sound when the view appears?
Or would it be more correct, not to subclass but instead call a separate method to play a sound when it appears?
Can anyone recommend a control that plays sound and looks prettier than UIAlertView?
you can achieve this by using AVAudioPlayer bellow code:-
Set dalagete of UIAlertView in .h file like:-
#interface ViewController : UIViewController <UIAlertViewDelegate>
in .m file
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/foo.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Title" message:#"message" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 1;
[audioPlayer play];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex==0) {
[audioPlayer stop];
}
}
EDIT
NOTE:- Do not forget to Add AVAudio framework And if you wish to sound playing till not press Button of UIAlertView then set audioPlayer.numberOfLoops = -1;
Related
I have a CollectionView with images and in the next ViewController I am recording a video using Av captured sessions and i am saving it in to the mobile document directory,Then i am coming back to the collection and i am reloading the collection view now i want the recored video in the collection view cell with out using any api.
I used the below code to save the recored video in the directory
'- (void)saveRecordedFile:(NSURL *)recordedFile {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary writeVideoAtPathToSavedPhotosAlbum:recordedFile
completionBlock:
^(NSURL *assetURL, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSString *title;
NSString *message;
if (error != nil) {
title = #"Failed to save video";
message = [error localizedDescription];
}
else {
title = #"Saved!";
message = nil;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
UIStoryboard *storybord=[UIStoryboard storyboardWithName:#"Main" bundle:nil];
shareViewController *shareview=[storybord instantiateViewControllerWithIdentifier:#"share"];
[self presentViewController:shareview animated:YES completion:nil];
});
}];
});
can any body help out to solve this problem.solution view code is appreciated. i recored video by referring this https://github.com/shu223/SlowMotionVideoRecorder
1) You can achieve it by getting the center frame of the video which you have stored in the document directory.
2) You can store the center frame image of the video to document directory so that you don't have to generate everytime.
3) Display video thumbnail inside collectionview.
Refer this link for get frame of the video :
Create thumbnail from a video url in IPhone SDK
EDIT:
NSString *videoPath = [videoURL path];
MPMoviePlayerViewController *videoPlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:videoPath]];
[self presentMoviePlayerViewControllerAnimated:videoPlayerView]; [videoPlayerView.moviePlayer play];
I'm developing an iOS application for a news website, the website has a live audio news channel, i have tried using AVAudioPlayer and did the following:
.h file:
#interface ViewController : UIViewController <AVAudioPlayerDelegate>
#property (strong, nonatomic) AVAudioPlayer *audioPlayer;
.m file (viewDidLoad):
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:#"http://198.178.123.23:8662/stream/1/;listen.mp3"];
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
_audioPlayer.delegate = self;
[_audioPlayer prepareToPlay];
}
}
But the application is giving me the following error:
2015-05-25 15:03:12.353 AudioPlayer[2043:421434] Error in audioPlayer: The operation couldn’t be completed. (OSStatus error 2003334207.)
I don't know what's wrong with this code.
Can anyone tell me where's the error in the code ?
Many thanks.
I think there is a better way to play the audio link in the default MPMoviePlayer with audio url. Rest of the things will be managed by default player.
EDIT :
NSURL *audioPath = [NSURL URLWithString:#"Your Audio URL"];
MPMoviePlayerViewController *mpViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:audioPath];
// Remove the movie player view controller from the "playback did finish" notification observers
[[NSNotificationCenter defaultCenter] removeObserver:mpViewController
name:MPMoviePlayerPlaybackDidFinishNotification
object:mpViewController.moviePlayer];
// Register this class as an observer instead
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(movieFinishedCallback:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:mpViewController.moviePlayer];
// Set the modal transition style of your choice
mpViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
// Present the movie player view controller
[self presentViewController:mpViewController animated:YES completion:nil];
// Start playback
[mpViewController.moviePlayer prepareToPlay];
[mpViewController.moviePlayer play];
You're getting an error because AVAudioPlayer doesn't support HTTP (meaning that you can't play media from the internet), so what you can do is use AVPlayer it's pretty much similar, here's an example :
- (void)viewDidLoad {
[super viewDidLoad];
NSString *urlAddress = #"http://198.178.123.23:8662/stream/1/;listen.mp3";
urlStream = [NSURL URLWithString:urlAddress];
self.audioPlayer = [AVPlayer playerWithURL:urlStream];
NSError *error;
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
[_audioPlayer prepareForInterfaceBuilder];
}
}
Hope my answer helped you :)
I am trying to add a video to display on my login screen. Here's my code:
import AVFoundation/AVFoundation.h
import MediaPlayer/MediaPlayer.h
import QuartzCore/QuartzCore.h
#interface AuthenticationViewController (){
MPMoviePlayerController *player;
}
#property (nonatomic, strong) MPMoviePlayerController *player;
#end
#implementation AnimatedLoginViewController
#synthesize player;
- (void)ViewDidLoad
CGRect screen = [[UIScreen mainScreen] bounds];
NSURL *movieUrl = [[NSBundle mainBundle] URLForResource:#"demo" withExtension:#"mp4"];
self.player = [[MPMoviePlayerController alloc] initWithContentURL:movieUrl];
player.view.frame = screen;
player.scalingMode = MPMovieScalingModeFill;
[self.player setControlStyle:MPMovieControlStyleNone];
[self.view addSubview:player.view];
[player prepareToPlay];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playVideo)
name:MPMoviePlayerReadyForDisplayDidChangeNotification
object:player];
[player play];
}
-(void)playVideo{
[player play];
}
All I get right now is a black screen and the video that is called demo.mp4 isn't showing when I access the view controller when running the app. Any suggestions?
I've just tried your code and it's working as expected for me.
Usually if the URL provided is nil or the file doesn't exist, the movie player is not able to locate it, hence the black screen.
I would first check to see that the file is being added to the bundle. You can do this from the project settings. The next steps would be to add code to ensure the file exists.
if (![[NSFileManager defaultManager] fileExistsAtPath:movieUrl.path]) {
NSLog(#"File doesn't exist at path: %#", movieUrl.path);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Load Error!" message:#"File doesn't exist" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if(actionSheet.tag == 2) {
if(buttonIndex != actionSheet.cancelButtonIndex) {
NSString *s = [actionSheet buttonTitleAtIndex:buttonIndex];
NSString *soundFile = [[NSBundle mainBundle] pathForResource:s ofType:#"m4a"];
NSURL *soundUrl = [NSURL fileURLWithPath:soundFile];
AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:soundUrl error:nil];
player.numberOfLoops = 0;
[player play];
}
}
}
When I place a breakpoint on [player play]; and step over, iPhone is playing the sound. Without breakpoint its not playing the sound. Why this is happening?
I think your project is enabled ARC.
When ARC enable local variables destroy after method execution.
So you have to declare your AVAudioPlayre object as global.
It will maintain your object till view destroy.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
What's the easiest way to play a music file such as Mp3 with pause button?
very very simple a button play and another button pause that music
These are the codes for the requested actions,
appSoundPlayer is a property of AVAudioPlayer declared in h file. Also this example plays a song in the resource folder.
#pragma mark -
#pragma mark *play*
- (IBAction) playaction {
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"songname" ofType:#"mp3"];
NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
self.soundFileURL = newURL;
[newURL release];
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
// Registers the audio route change listener callback function
AudioSessionAddPropertyListener (
kAudioSessionProperty_AudioRouteChange,
audioRouteChangeListenerCallback,
self
);
// Activates the audio session.
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: nil];
self.appSoundPlayer = newPlayer;
[newPlayer release];
[appSoundPlayer prepareToPlay];
[appSoundPlayer setVolume: 1.0];
[appSoundPlayer setDelegate: self];
[appSoundPlayer play];
[stopbutton setEnabled:YES];
[playbutton setEnabled: NO];
playbutton.hidden=YES;
pausebutton.hidden =NO;
}//playbutton touch up inside
#pragma mark -
#pragma mark *pause*
-(IBAction)pauseaction {
[appSoundPlayer pause];
pausebutton.hidden = YES;
resumebutton.hidden = NO;
}//pausebutton touch up inside
#pragma mark -
#pragma mark *resume*
-(IBAction)resumeaction{
[appSoundPlayer prepareToPlay];
[appSoundPlayer setVolume:1.0];
[appSoundPlayer setDelegate: self];
[appSoundPlayer play];
playbutton.hidden=YES;
resumebutton.hidden =YES;
pausebutton.hidden = NO;
}//resumebutton touch up inside
#pragma mark -
#pragma mark *stop*
-(IBAction)stopaction{
[appSoundPlayer stop];
[playbutton setEnabled:YES];
[stopbutton setEnabled:NO];
playbutton.hidden=NO;
resumebutton.hidden =YES;
pausebutton.hidden = YES;
}//stopbutton touch up inside
For short sounds or when the MP3 does not play well on the suggested code you can always use:
SystemSoundID soundID;
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/sound.mp3", [[NSBundle mainBundle] resourcePath]]];
AudioServicesCreateSystemSoundID((CFURLRef)url, &soundID);
AudioServicesPlaySystemSound (soundID);
Don't forget to add:
#import <AudioToolbox/AudioToolbox.h>
well here is a good tutorial available.
The theme is
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
and when you want to pause;
[audioPlayer pause];
hope this helps.
I'm afraid the answer stated no longer works in iOS 7 and above. You will need to use the following code:
in the header file (.h)
In order to handle the delegate methods like when the playing of the audio has finished audioPlayerDidFinishPlaying:, inherit from AVAudioPlayerDelegate .
#property (nonatomic, strong) AVAudioPlayer *player;
in the implementation file (.m)
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: resourceName
ofType: #"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
error: nil];
_player = newPlayer;
[_player prepareToPlay];
[_player setDelegate: self];
[_player play];
I like simple code and here is my solution : (Remember to add switch button to get music play. Have fun)
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#interface ViewController ()
{
NSURL* bgURL;
AVAudioPlayer* bgPlayer;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
bgURL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"mp3"]];
bgPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:bgURL error:nil];
}
#pragma mark AVAudioPlayer
- (IBAction)toggleMusic:(UISwitch*)sender {
NSLog(#"togging music %s", sender.on ? "on" : "off");
if (bgPlayer) {
if (sender.on) {
[bgPlayer play];
}
else {
[bgPlayer stop];
}
}
}
The Apple documentation here should have everything you need to know.
DIRAC API is free and quite easy to use.
We've used it in my talking robot app http://itunes.apple.com/us/app/daidai/id484833168 and it has been amazing to me how it manages to change the speed and pitch of voice
http://www.dspdimension.com/download/
The oalTouch sample code on the Apple iOS developer web site does what you want, and is ready to run.
It also shows how to test if another app (eg ipod) is playing a file already, which is handy if you want to allow your users to listen to their own music instead of yours.