0

我目前正在尝试为 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];
}
}

由于我仍在学习,我对代码的奇怪布局表示歉意。我现在才从阅读另一个问题中偶然发现有关制作这些课程的信息。哈哈

4

1 回答 1

0

好的,我已经想通了。

与其像我在上面的代码中那样一遍又一遍地创建对象,我应该在 viewdidload 中分配和初始化播放器,而不是像我那样在 IBAction 中进行。

这就是我所做的,以防其他人遇到同样的问题:

锁定位置.h

@interface LockOnLocation : UIViewController {

AudioPlayer1 *player;
...

锁定位置.m

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

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

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

于 2012-11-04T22:32:20.673 回答