AVAudioPlayer没有响应停止命令?

时间:2012-11-04 15:47:53

标签: class ios5 xcode4.2 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];
}
}

我为代码的奇怪布局道歉,因为我还在学习。我现在才发现有关通过阅读另一个问题偶然完成这些课程。洛尔

1 个答案:

答案 0 :(得分:0)

好的,我已经明白了。

不是像我在上面的代码中那样反复创建对象,而是应该在viewdidload中分配和初始化播放器,而不是像我一样在IBAction中执行它。

这就是我做过的事情,其他人遇到同样的问题:

LockonLocation.h

@interface LockOnLocation : UIViewController {

AudioPlayer1 *player;
...

LockonLocation.m

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

我使用与上面相同的代码来播放音频,这是正确的。

如果有人对我或任何其他成员有任何其他建议,我很乐意听取您的意见......