хотел воспроизвести мой звуковой файл, когда происходит событие уведомления, а затем остановить - PullRequest
2 голосов
/ 28 октября 2011

Я делаю Будильник, в котором я хочу, чтобы когда выбранное время через Datepicker происходило вместо только уведомления и появления значка, я хотел воспроизвести свой собственный звуковой файл, то есть jet.wav (это менее 30 секунд и в формате .wav). Я хочу, чтобы как только появилось моё уведомление, он воспроизводил звук, а когда я щелкаю по приложению или представлению оповещения, он должен остановиться. Так может кто-нибудь, пожалуйста, помогите мне. вот что я пытаюсь: -

Код: -

@class The420DudeViewController;

@interface The420DudeAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    The420DudeViewController *viewController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet The420DudeViewController *viewController;

extern NSString *kRemindMeNotificationDataKey;






@implementation The420DudeAppDelegate

@synthesize window;
@synthesize viewController;

NSString *kRemindMeNotificationDataKey = @"kRemindMeNotificationDataKey";

#pragma mark -
#pragma mark === Application Delegate Methods ===
#pragma mark -



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    Class cls = NSClassFromString(@"UILocalNotification");
    if (cls) {
        UILocalNotification *notification = [launchOptions objectForKey:
                                             UIApplicationLaunchOptionsLocalNotificationKey];

        if (notification) {
            NSString *reminderText = [notification.userInfo 
                                      objectForKey:kRemindMeNotificationDataKey];
            [viewController showReminder:reminderText];
        }
    }

    application.applicationIconBadgeNumber = 0;

    [window addSubview:viewController.view];
    [self.window makeKeyAndVisible];

    return YES;
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    application.applicationIconBadgeNumber = 0;
}

- (void)application:(UIApplication *)application 
didReceiveLocalNotification:(UILocalNotification *)notification {

    application.applicationIconBadgeNumber = 0;
    NSString *reminderText = [notification.userInfo
                              objectForKey:kRemindMeNotificationDataKey];
    [viewController showReminder:reminderText];
}

- (void)dealloc {
    [viewController release];
    [window release];
    [super dealloc];
}


@end




@interface The420DudeViewController : UIViewController {

    IBOutlet UINavigationBar *titleBar;
    IBOutlet UIButton *setAlarmButton;
    IBOutlet UIDatePicker *selectTimePicker;
    AVAudioPlayer *player;

}

@property(nonatomic, retain) IBOutlet UINavigationBar *titleBar;
@property(nonatomic, retain) IBOutlet UIButton *setAlarmButton;
@property(nonatomic, retain) IBOutlet UIDatePicker *selectTimePicker;

-(IBAction)onTapSetAlarm;
- (void)showReminder:(NSString *)text;

@end




@implementation The420DudeViewController

@synthesize titleBar,setAlarmButton,selectTimePicker;


#pragma mark -
#pragma mark === Initialization and shutdown ===
#pragma mark -

- (void)viewDidLoad {
    [super viewDidLoad];
    selectTimePicker.minimumDate = [NSDate date];
}

- (void)viewDidUnload {

    [super viewDidUnload];
    self.setAlarmButton = nil;
    self.selectTimePicker = nil;
}
/*
-(void)viewWillAppear:(BOOL)animated
{
    NSString *path = [[NSBundle mainBundle]pathForResource:@"Song1" ofType:@"mp3"];
    NSURL *url = [NSURL fileURLWithPath:path];

    player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
//  [player play];
}
 */
-(IBAction)onTapSetAlarm
{
    [[UIApplication sharedApplication] cancelAllLocalNotifications];

    Class cls = NSClassFromString(@"UILocalNotification");
    if (cls != nil) {

        UILocalNotification *notif = [[cls alloc] init];
        notif.fireDate = [selectTimePicker date];
        notif.timeZone = [NSTimeZone defaultTimeZone];

        notif.alertBody = @"Did you forget something?";
        notif.alertAction = @"Show me";
        notif.repeatInterval = NSDayCalendarUnit;
    //  notif.soundName = UILocalNotificationDefaultSoundName;
        notif.soundName = [[NSBundle mainBundle]pathForResource:@"jet" ofType:@"wav"];
        notif.applicationIconBadgeNumber = 1;

        NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"Mayank"
                                                             forKey:kRemindMeNotificationDataKey];
        notif.userInfo = userDict;

        [[UIApplication sharedApplication] scheduleLocalNotification:notif];
        [notif release];
    }

/*
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm a"];

NSDate *selectedDate = [[NSDate alloc] init];
selectedDate = [selectTimePicker date];

NSString *theTime = [timeFormat stringFromDate:selectedDate];

UIAlertView *alert = [[UIAlertView alloc]
                      initWithTitle:@"Time selected" message:theTime delegate:nil cancelButtonTitle:@"YES" otherButtonTitles:nil];

[alert show];
[alert release];
//  [timeFormat release];
//  [selectedDate release];

 */
}


#pragma mark -
#pragma mark === Public Methods ===
#pragma mark -

- (void)showReminder:(NSString *)text {

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Reminder" 
                                                        message:@" TEXT " delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}

- (void)dealloc {
    [super dealloc];
    [titleBar release];
    [setAlarmButton release];
    [selectTimePicker release];
}

@end

1 Ответ

1 голос
/ 28 октября 2011

Согласно документации для soundName, вы должны

указать имя файла (включая расширение) звукового ресурса в основном комплекте приложения

Поэтому я предлагаю вам изменить эту строку -[The420DudeViewController onTapSetAlarm]:

    notif.soundName = [[NSBundle mainBundle]pathForResource:@"jet" ofType:@"wav"];

на следующую:

    notif.soundName = @"jet.wav";
...