2012-11-04 48 views
0

我目前正在嘗試使用AVAudioPlayer的自定義類,並且所有工作都非常適合播放音頻文件,但是當它停止所述文件時,它會跳過停止命令並在當前文件上播放另一個文件,AVAudioPlayer沒有響應停止命令?

如果任何人有任何想法,爲什麼發生這種情況,我真的很感激幫助。

下面是我的AudioPlayer1.h文件:

#import <Foundation/Foundation.h> 
#import "AVFoundation/AVAudioPlayer.h" 
#import <AVFoundation/AVFoundation.h> 

@interface AudioPlayer1 : NSObject <AVAudioPlayerDelegate> { 

    AVAudioPlayer *player; 

    BOOL playing; 
    NSTimeInterval duration;   
} 

@property (nonatomic, assign) AVAudioPlayer *player; 
@property(readonly, getter=isPlaying) BOOL playing; 
@property (readonly) NSTimeInterval duration; 


-(void)GetSoundFileDuration:(NSString *) sound_file_name; 
-(void)play; 
-(void)stop; 

-(void)setVolume:(float) volume; 

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag; 
- (void)PlaySoundFile:(NSString *) sound_file_name; 

- (void)notPlaying; 

@end 

下面是AudioPlayer1.m文件的內容:

#import "AudioPlayer1.h" 

@implementation AudioPlayer1 

@synthesize player; 
@synthesize duration; 
@synthesize playing; 

- (id)init 
{ 
self = [super init]; 
if (self != nil) 
{ 
    player = [[AVAudioPlayer alloc] init]; 
    [player initWithContentsOfURL:nil error:nil]; 
    player.delegate = self; 
} 
return self; 
} 

- (void) setVolume:(float)volume 
{ 
[player setVolume:volume]; 
} 

- (void)PlaySoundFile:(NSString *) sound_file_name 
{ 
[player stop]; 
NSURL *sound_file = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:sound_file_name ofType:@"mp3"]]; 

[player initWithContentsOfURL:sound_file error:nil]; 
[player prepareToPlay]; 
playing = YES; 
[sound_file release]; 
} 

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag 
{ 
NSLog(@"audioPlayerDidFinishPlaying"); 
playing = NO; 
} 


- (void) play 
{ 
NSLog(@"Play Called"); 
[player setVolume:0.1]; 
[player play]; 
playing = YES; 
} 

- (void) stop 
{ 
NSLog(@"Stop Called"); 
[player setVolume:0.0]; 
[player stop]; 
playing = NO; 
} 


-(void)GetSoundFileDuration:(NSString *) sound_file_name 
{ 
NSLog(@"%@",duration); 
} 

-(void) notPlaying 
{ 
playing = NO; 
} 

@end 

及以下,將啓動音頻代碼:

- (IBAction)WPNaritive01:(id)sender 
{ 
AudioPlayer1 * player = [[AudioPlayer1 alloc] init ]; 

if (player.playing == YES) 
{ 
    [player stop]; 
} 

if (player.playing == NO) 
{ 
    [player PlaySoundFile:@"1"]; 
    [player setVolume:0.1]; 
    [player play]; 
} 
} 

我對代碼的奇怪佈局表示歉意,因爲我還在學習。我現在才發現,通過閱讀另一個問題偶然地製作這些課程。大聲笑

回答

0

好吧,我已經知道了。

不是像我在上面的代碼中那樣反覆創建對象,而是應該在viewdidload中分配和初始化播放器,而不是像IB一樣在IBAction中完成它。

這是我做過什麼櫃面任何人都遇到了同樣的問題:

LockonLocation.h

@interface LockOnLocation : UIViewController { 

AudioPlayer1 *player; 
... 

LockonLocation.m

- (void)viewDidLoad 
player = [[AudioPlayer1 alloc] init ]; 
... 

而且我用同樣的代碼如上播放音頻以保證正確。

如果有人對我或任何其他成員有任何其他建議,我很樂意聽取您的意見...