AVAudioPlayer 没有响应停止命令?
Posted
技术标签:
【中文标题】AVAudioPlayer 没有响应停止命令?【英文标题】:AVAudioPlayer not responding to stop command? 【发布时间】:2012-11-04 15:47:52 【问题描述】:我目前正在尝试为 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】:好的,我想通了。
与其像我在上面的代码中那样一遍又一遍地创建对象,我应该在 viewdidload 中分配和初始化播放器,而不是像我那样在 IBAction 中进行。
这就是我所做的,以防其他人遇到同样的问题:
LockonLocation.h
@interface LockOnLocation : UIViewController
AudioPlayer1 *player;
...
LockonLocation.m
- (void)viewDidLoad
player = [[AudioPlayer1 alloc] init ];
...
我使用与上面相同的代码来播放音频,所以这是正确的。
如果有人对我或任何其他成员有任何其他建议,我很乐意听取您的意见......
【讨论】:
以上是关于AVAudioPlayer 没有响应停止命令?的主要内容,如果未能解决你的问题,请参考以下文章
iPhone:MPMusicPlayerController 停止 AVAudioPlayer
当音频输入添加到 AVCaptureSession 时 AVAudioPlayer 停止
播放音乐时,我的音频应用程序中没有收到通知或消息的声音 | AV音频播放器