Cant stop AVAudioPlayer from playing - iphone

Here is my code
AppDelegate.m
I use this code to start AVAudioPlayer. It works fine.
#import "AppDelegate.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
resourcePath = [resourcePath stringByAppendingString:#"/Helloween.mp3"];
NSLog(#"Path to play: %#", resourcePath);
NSError* err;
//Initialize our player pointing to the path to our resource
backgroundMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:resourcePath] error:&err];
if( err ){
//bail!
NSLog(#"Failed with reason: %#", [err localizedDescription]);
}
else{
//set our delegate and begin playback
backgroundMusic.delegate = self;
[backgroundMusic play];
backgroundMusic.numberOfLoops = -1;
backgroundMusic.currentTime = 0;
backgroundMusic.volume = 1.0;
}
// Override point for customization after application launch.
return YES;
}
In AppDelegate.h I add framework and AVAudioPlayer
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate> {
AVAudioPlayer *backgroundMusic;
}
#property(nonatomic,retain) AVAudioPlayer *backgroundMusic;
#property (strong, nonatomic) UIWindow *window;
#end
In ViewController.m i also add framework AVFoundation and import AppDelegate.h
#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
#import <CoreData/CoreData.h>
#define fName #"data.plist"
#define kNames #"data.plist"
#import <AVFoundation/AVFoundation.h>
#import "AppDelegate.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize backgroundMusic;
-(IBAction)stopMusic:(id)sender {
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
[appDelegate.backgroundMusic stop];
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//set the position of the button
button.frame = CGRectMake(100, 100, 20, 20);
button.backgroundColor = [UIColor whiteColor];
[button addTarget:self action:#selector(stopMusic:) forControlEvents:UIControlEventTouchUpInside];
//add the button to the view
[self.view addSubview:button];
ViewController.h
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import <CoreData/CoreData.h>
#define kNames #"data.plist"
#import <AVFoundation/AVFoundation.h>
#interface ViewController : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer *backgroundMusic;
}
I need stop the AudioPlayer with button.
Here is my code
AppDelegate.m
I use this code to start AVAudioPlayer.
#import "AppDelegate.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
resourcePath = [resourcePath stringByAppendingString:#"/Helloween.mp3"];
NSLog(#"Path to play: %#", resourcePath);
NSError* err;
//Initialize our player pointing to the path to our resource
backgroundMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:resourcePath] error:&err];
if( err ){
//bail!
NSLog(#"Failed with reason: %#", [err localizedDescription]);
}
else{
//set our delegate and begin playback
backgroundMusic.delegate = self;
[backgroundMusic play];
backgroundMusic.numberOfLoops = -1;
backgroundMusic.currentTime = 0;
backgroundMusic.volume = 1.0;
}
// Override point for customization after application launch.
return YES;
}
AppDelegate.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate> {
AVAudioPlayer *backgroundMusic;
}
-(IBAction)stopMus:(id)sender;
#property(nonatomic,retain) AVAudioPlayer *backgroundMusic;
#property (strong, nonatomic) UIWindow *window;
#end
ViewController.m
#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
#import <CoreData/CoreData.h>
#define fName #"data.plist"
#define kNames #"data.plist"
#import <AVFoundation/AVFoundation.h>
#import "AppDelegate.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize backgroundMusic;
-(IBAction)stopMusic:(id)sender {
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
[appDelegate.backgroundMusic stop];
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//set the position of the button
button.frame = CGRectMake(100, 100, 20, 20);
button.backgroundColor = [UIColor whiteColor];
[button addTarget:self action:#selector(stopMusic:) forControlEvents:UIControlEventTouchUpInside];
//add the button to the view
[self.view addSubview:button];
ViewController.h
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import <CoreData/CoreData.h>
#define kNames #"data.plist"
#import <AVFoundation/AVFoundation.h>
#interface ViewController : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer *backgroundMusic;
}
I need stop the AudioPlayer with button.

First, add UIButton to the UIView like this:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//set the position of the button
button.frame = CGRectMake(0, 0, 0, 0);
[button addTarget:self action:#selector(yourMethod:) forControlEvents:UIControlEventTouchUpInside];
//add the button to the view
[self.view addSubview:button];
Then,
-(IBAction)yourMethod:(id)sender {
[backgroundMusic stop];
}
After your done with the button, you can remove it via [button removeFromSuperView];
I think, something like that should work :) Please ask if your having problem with my answer.

Related

how to drag selected string in uitextview from out of the textview.?

*iam a beginner in iphone development.
i have one problem in uitextview...wat iam trying to do is dragging the the selected string in uitextview from out of the textview...and drag it to the tabbarcontroller is it possible plz any on help me on this....*this is the code ihave return up to now....plz help me
#
import <UIKit/UIKit.h>
#import "TabViewController.h"
#class TabBarViewController;
#interface TabBarAppDelegate : UIResponder <UIApplicationDelegate,UITabBarControllerDelegate>
{
TabBarViewController *txtviewcontroller;
UITabBarController *tabbar;
NSArray *viewcontrollerarray;
}
#property(nonatomic,retain)NSArray *viewcontrollerarray;
#property(nonatomic,strong)UITabBarController *tabbar;
#property(nonatomic,retain)TabBarViewController *txtviewcontroller;
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) TabBarViewController *viewController;
#end
#import "TabBarAppDelegate.h"
#import "TabViewController.h"
#implementation TabBarAppDelegate
#synthesize txtviewcontroller,tabbar,viewcontrollerarray;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor=[UIColor whiteColor];
self.tabbar=[[UITabBarController alloc]init];
txtviewcontroller=[[TabBarViewController alloc]init];
tabbar.delegate=self;
viewcontrollerarray=[[NSArray alloc]initWithObjects:txtviewcontroller, nil];
self.tabbar.viewControllers=viewcontrollerarray;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
self.viewController = [[TabBarViewController alloc] initWithNibName:#"TabBarViewController_iPhone" bundle:nil];
} else {
self.viewController = [[TabBarViewController alloc] initWithNibName:#"TabBarViewController_iPad" bundle:nil];
}
self.window.rootViewController = self.tabbar;
[self.window makeKeyAndVisible];
return YES;
}
#import <UIKit/UIKit.h>
#interface TabBarViewController : UIViewController
{
UITextView *textview;
}
#property(nonatomic,retain)UITextView *textview;
#end
#import "TabViewController.h"
#import "TabBarAppDelegate.h"
#include <QuartzCore/CoreAnimation.h>
#interface TabBarViewController ()
#end
#implementation TabBarViewController
#synthesize textview;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.title=#"firstname";
CGRect textViewFrame = CGRectMake(20.0f, 20.0f, 280.0f, 124.0f);
textview = [[UITextView alloc] initWithFrame:textViewFrame];
textview.backgroundColor=[UIColor clearColor];
textview.textColor=[UIColor blackColor];
textview.editable=NO;
NSString *filePath=[[NSBundle mainBundle]pathForResource:#"satyadetails" ofType:#"txt"];
NSString *contentString=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
textview.text=contentString;
textview.layer.borderWidth = 3.0f;
textview.layer.borderColor = [[UIColor grayColor] CGColor];
textview.returnKeyType = UIReturnKeyDone;
[self.view addSubview:textview];
enter code here
}
Step 1. Get event when user touches inside textview (You can get that by UITextView's Delegate (startEditing delegate))
Step 2. Add a UILabel on ur view giving position where user touches in textview and giving text as that of textview and giving clear color as backgroundcolor. (Do this inside delegate of textview)
Step 3. Inside touches move of ur view change the positions of ur label dynamically according to touches.
Step 4. When user moves its touches till dropping textview delegate will be called check there if(textview==droppingtextview) then put draggingtextview.text=label.text. and remove label from superview.

Passing values from second view to firstView in Xcode

I have been stuck here.
I have a NSString in Appdelegate. And I have two views called firstview,second view.In first view I have a label and set text from stringvariable which is in Appdelegate .When I click on the button in first view,It goes to the secondview(added the second view to first view as a subview).In second view I have a back button.when I click the back button it is displaying the first view ( Here I am setting the value which is in the appdelegate.And then used this [self.view removeFromSuperview]).The Problem is first view is appearing but label value is not updating.Can any body tell me how to update the Labeltext.Kindly tell me.
Appdelegate.h
#import <UIKit/UIKit.h>
#class FirstView;
#interface AppDelegate : UIResponder <UIApplicationDelegate>
{
NSString *str1;
}
#property (nonatomic,retain) NSString *str1;
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) ViewController *viewController;
#end
Appdelegate.m
#import "AppDelegate.h"
#import "FirstView.h"
#implementation AppDelegate
#synthesize window = _window;
#synthesize viewController = _viewController;
#synthesize str1;
- (void)dealloc
{
[_window release];
[_viewController release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.viewController = [[[FirsView alloc] initWithNibName:#"FirstView" bundle:nil] autorelease];
self.str1 = #"view1";
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
FirstView.h
#import <UIKit/UIKit.h>
#import "secondView.h"
#interface FirstView : UIViewController
{
IBOutlet UILabel *btn;
secondView *cont;
}
-(IBAction)gotoView2:(id)sender;
#end
FirstView.m
#import "FirstView.h"
-(IBAction)gotoView2:(id)sender
{
cont = [[secondView alloc] initWithNibName:#"secondView" bundle:nil];
[self.view addSubview:cont.view];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
AppDelegate *del = [[UIApplication sharedApplication] delegate];
[btn setTitle:del.str1];
}
**SecondView.h**
#import <UIKit/UIKit.h>
#interface SecondView : UIViewController
{
}
-(IBAction)goBack:(id)sender;
#end
SecondView
#import "SecondView.h"
#import "AppDelegate.h"
#implementation SecondView
-(IBAction)gotoView1:(id)sender
{
AppDelegate *del = [[UIApplication sharedApplication] delegate];
[del setStr1:#"Home"];
[self.view removeFromSuperView];
}
There is a pattern how to do such things. You should define a protocol like this:
#protocol FirstViewDelegate <NSObject>
- (void)didDismissSecondView;
#end
Your first view should conform to this protocol:
#interface FirstView: UIViewController <FirstViewDelegate> {
...
in its implementation add function didDismissSecondView:
- (void) didDismissSecondView
{
AppDelegate *del = [[UIApplication sharedApplication] delegate];
[btn setTitle:del.str1];
}
Your second view has to have a property
#interface SecondView : UIViewController
{
id<FirstViewDeledate> delegate;
}
#property (nonatomic, retain) id<FirstViewDeledate> delegate;
When you show your second view from the first view set its delegate to self of first view
in your function:
-(IBAction)gotoView2:(id)sender
{
SecondView *aView = [[SecondView alloc] init] // or whatever
...//other initialization code
aView.delegate = self;
... // show it
}
and before you dismiss the second view:
-(IBAction)gotoView1:(id)sender
{
AppDelegate *del = [[UIApplication sharedApplication] delegate];
[del setStr1:#"Home"];
[self.delegate didDismissSecondView];
[self.view removeFromSuperView];
}
And you done.
A bit long, but works.

Dismiss MPMoviePlayerController on screen touch

I followed this tutorial, and included a video player in my app.
But the problem is that i want to hide the controls, and be able to dismiss the video on screen touch.
I tried putting a big transparent button in front of the video that triggers the dismiss function, but with no luck. the video will always be over the button and the function will never be called.
Is there another way of doing it?
ty
**Hi I think AVPlayer is become more suitable to you,You can use it as below and then add subview if you want to play and if you want to stop remove it from super view
** #import"AVFoundation/AVFoundation.h"
**For creating Player List:
NSString *path1 = [[NSBundle mainBundle] pathForResource:#"hello" ofType:#"mp4"];
AVPlayerItem *first = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:path1]];
player= [AVPlayer playerWithPlayerItem:first];
[self.playerView setPlayer:player];
[player play];
** You have to make uiview for playerview in it :
(id)initWithFrame:(CGRect)frame {self = [super initWithFrame:frame];
if (self) {
// Initialization code.
}
return self;
}
+ (Class)layerClass {
return [AVPlayerLayer class];
}
-(AVPlayer*)player {
return [(AVPlayerLayer *)[self layer] player];
}
-(void)setPlayer:(AVPlayer *)player {
[(AVPlayerLayer *)[self layer] setPlayer:player];
}
PlayerViewControll .H
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface PlayerView : UIView UILabel *pageNumberLabel;
int pageNumber;
}
#property (nonatomic, retain) AVPlayer *player;
- (id)initWithPageNumber:(int)page;
PlayerView .M
#import "PlayerView.h"
#implementation PlayerView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {}
return self;
}
+ (Class)layerClass {
return [AVPlayerLayer class];
}
- (AVPlayer*)player {
return [(AVPlayerLayer *)[self layer] player];
}
- (void)setPlayer:(AVPlayer *)player {
[(AVPlayerLayer *)[self layer] setPlayer:player];
}
MainViewControll .H
#import <AVFoundation/AVFoundation.h>
#import "PlayerView.h"
#interface MainViewController : UIViewController {
IBOutlet PlayerView *playerView;
NSString *url;
AVPlayer *player;
NSMutableArray *arrIteam;
}
#property(nonatomic,retain) NSMutableArray *arrIteam;
#property (nonatomic, retain) AVPlayer *player;
#property(nonatomic ,retain)IBOutlet PlayerView *playerView;
PlayerView.M
#import "MainViewController.h"
#import <QuartzCore/QuartzCore.h>
#implementation MainViewController
#synthesize player,playerView,arrIteam;
- (void)viewDidLoad {
NSString *path1 = [[NSBundle mainBundle] pathForResource:#"hello" ofType:#"mp4"];
AVPlayerItem *first = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:path1]];
arrIteam = [[NSMutableArray alloc] initWithObjects:first,second, third,fourth,nil];
player=[AVPlayer playerWithPlayerItem:[arrIteam objectAtIndex:i]];
[self.playerView setPlayer:player];
[player play];
[super viewDidLoad];
}
You should use UIGestureRecognizer class. See manual for details. Or read this tutorial.
Use this code.
UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(stopPlayer)];
[self.view addGestureRecognizer:gestureRecognizer];
gestureRecognizer.cancelsTouchesInView = NO;
[gestureRecognizer release];
in view didload;
And in
- (void) stopPlayer
stop the player and release this player from view.
Hope it helps you.
i just found the solution to my problem in another question asked here. after some minor modifications, the code worked as expected. thank you all.

change view's property from method of other class

I'm trying to remotely adjust an object myImageView's alphato 0 of MyViewControllerclass From Another class Assistant(it's a NSObject subclass).
in Assistant.h
#import <Foundation/Foundation.h>
#class MyViewController;
#interface Assistant : NSObject {
MyViewController *myViewController;
UIImageView *button;
}
- (void)adjustAlpha:(id)sender;
#property (nonatomic, retain) UIImageView *button;
in Assistant.m
#import "MyViewController.h"
#implementation Assistant
#synthesize button;
- (id)init
{
self = [super init];
if (self)
{
myViewController = [[MyViewController alloc] init];
NSLog(#"alloced?: %#", myViewController ? #"YES" : #"NO");
}
return self;
}
- (void)adjustAlpha:(id)sender
{
NSLog(#"method called");
myViewController.myImageView.alpha = 0;
}
the method did get called, But myViewController.myImageView.alpha didn't change, why? where i need to fix? thank you for reading ^_^
Edit
This is MyViewController class:
MyViewController.h
#class Assistant;
#class MyAppAppDelegate;
#interface MyViewController : UIViewController <UITextViewDelegate, UIScrollViewDelegate>
{
UIImageView *myImageView;
Assistant *assistant;
}
#property (nonatomic, retain) UIImageView *myImageView;
MyViewController.m
#import "MyViewController.h"
#import "Assistant.h"
#implementation MyViewController
#synthesize myImageView;
- (void)viewDidLoad
{
[super viewDidLoad];
assistant = [[Assistant alloc] init];
myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,320,460);
[self.view addSubview: myScrollView];
myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"weather.png"]];
myImageView.frame = CGRectMake(19, 54, 48, 48);
myImageView.userInteractionEnabled = YES;
[myScrollView addSubview:myImageView];
//this button uses to call adjustAlpha
assistant.button = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"button.png"]];
assistant.button.frame = CGRectMake(19, 126, 48, 48);
assistant.button.userInteractionEnabled = YES;
[myScrollView addSubview:assistant.button];
//here is how i call adjustAlpha:
assistant.adjustAlphaTap = [[UITapGestureRecognizer alloc] initWithTarget:assistant action:#selector(adjustAlpha:)];
[assistant.button addGestureRecognizer:assistant.adjustAlphaTap];
}
this question got complex and need some experiments, so just hanging there, will make it clear when i have time. for developer met the same problems: declare the object you need to access in a singleton class, can be easily accessed from any other classes, and Merry Christmas!
This will only work if myImageView is declared as a global scope variable (also called an iVar) in the .h file of your MyViewController class AND that it has a property of (nonatomic, retain) with a matching #synthesize in the .m.
If this sounds like what you're doing then can you please post the contents of your MyViewController h and m files.
If you have everything defined like Thomas described, can you check if the adjustAlpha method is called on the main thread?

How to implement a modal date picker?

I am using code from Ed Marty's answer for the question here but am having real trouble with a few bits.
On the click of a button I have got the datepicker appearing, but the 'done' button however isn't. I am also getting an error from the line:
[delegate datePickerController:controller didPickDate:datePicker.date];
Error message:
'controller' undeclared (first use in this function)
All in all I have 6 files:
ModalDatePickerViewController.m
ModalDatePickerViewController.h
ModalDatePickerAppDelegate.m
ModalDatePickerAppDelegate.h
DatePickerController.m
DatePickerController.h
My DatePickerController.h is looking like:
#import <UIKit/UIKit.h>
#class DatePickerController;
#protocol DatePickerControllerDelegate
- (void) datePickerController:(DatePickerController *)controller didPickDate:(NSDate *)date;
#end
#interface DatePickerController : UIViewController {
UIDatePicker *datePicker;
NSObject <DatePickerControllerDelegate> *delegate;
}
#property (nonatomic, retain) UIDatePicker *datePicker;
#property (nonatomic, assign) NSObject <DatePickerControllerDelegate> *delegate;
#end
and the DatePickerController.m:
#import "DatePickerController.h"
#implementation DatePickerController
#synthesize datePicker;
#synthesize delegate;
- (void) loadView {
self.view = [[[UIView alloc] init] autorelease];
self.datePicker = [[[UIDatePicker alloc] init] autorelease];
[self.view addSubview:self.datePicker];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:#"Done" forState:UIControlStateNormal];
button.center = CGPointMake(160,230);
[button addTarget:self action:#selector(done) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:button];
}
- (void) done {
[delegate datePickerController:controller didPickDate:datePicker.date];
}
- (void) dealloc {
[datePicker release];
[super dealloc];
}
#end
On the main view I have a button that call this class as below:
#import "ModalDatePickerViewController.h"
#implementation ModalDatePickerViewController
- (void) pickDate {
DatePickerController *screen = [[[DatePickerController alloc] init] autorelease];
screen.delegate = self;
[self presentModalViewController:screen animated:YES];
}
- (void) datePickerController:(DatePickerController *)controller didPickDate:(NSDate *)date {
//[self doSomethingWithDate:date];
[controller dismissModalViewControllerAnimated:YES];
}
- (IBAction)HitMe:(id)sender {
[self pickDate];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
}
- (void)dealloc {
[super dealloc];
}
#end
and:
#import <UIKit/UIKit.h>
#import "DatePickerController.h"
#interface ModalDatePickerViewController : UIViewController <DatePickerControllerDelegate> {
}
- (IBAction)HitMe:(id)sender;
#end
On this line:
[delegate datePickerController:controller didPickDate:datePicker.date];
try replacing controller with self.