我目前正在尝试为 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];
}
}
由于我仍在学习,我对代码的奇怪布局表示歉意。我现在才从阅读另一个问题中偶然发现有关制作这些课程的信息。哈哈