我可以直接在 ViewController 中使用 AVAudioPlayer 框架播放 mp3 文件作为按钮的操作,但是如果我想播放相同的 mp3 调用 NSObject 类中的选择器,则失败。谢谢你的建议。
从 ViewController (audioPlayerDemo.xcodeproj) 播放 mp3 并且它可以工作:
AVFoundation.framework 包含在 frameworks 文件夹中
APDViewController.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface APDViewController : UIViewController <AVAudioPlayerDelegate>
{
}
@property (strong,nonatomic) AVAudioPlayer *audioPlay;
- (IBAction)play:(id)sender;
APDViewController.m
@implementation APDViewController
@synthesize audioPlay;
- (IBAction)play:(id)sender
{
NSError *error = nil;
NSData *dataAudio = [[NSData alloc] initWithContentsOfFile:
@"/Users/User/Documents/AudioPlayerDemo/AudioPlayerDemo/hello world.mp3"options:0 error:&error];
if(error){
NSLog(@" error loading data: %@ ", [error localizedDescription]);
}
else{
audioPlay = [[AVAudioPlayer alloc] initWithData:dataAudio error:&error];
if(error){
NSLog(@" error loading audio: %@ ", [error localizedDescription]);
}
else{
audioPlay.delegate = self;
[audioPlay prepareToPlay];
[audioPlay play];
}
}
}
-(void)audioPlayerDidFinishPlaying:
(AVAudioPlayer *)player successfully:(BOOL)flag
{
if (player == audioPlay){
audioPlay = nil;
NSLog(@"audioplay = nil");
}
}
但是,如果我想播放调用 NSObject 类 (AudioPlayClass.xcodeproj) 的相同 .mp3,则没有错误,也没有任何声音。这是不起作用的代码:
AVFoundation.framework 包含在 frameworks 文件夹中
APCplayObject.h
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@interface APCplayObject : NSObject <AVAudioPlayerDelegate>
{
}
@property (strong,nonatomic) AVAudioPlayer *audioPlay;
- (void)playAudio;
@end
APCplayObject.m
#import "APCplayObject.h"
@implementation APCplayObject
@synthesize audioPlay;
-(void)playAudio{
NSError *error = nil;
NSData *dataAudio = [[NSData alloc] initWithContentsOfFile:
@"/Users/User/Documents/AudioPlayerClass/AudioPlayerClass/hello world.mp3"options:0 error:&error];
if(error){
NSLog(@" error loading data: %@ ", [error localizedDescription]);
}
else{
audioPlay = [[AVAudioPlayer alloc] initWithData:dataAudio error:&error];
if(error){
NSLog(@" error loading audio: %@ ", [error localizedDescription]);
}
else{
audioPlay.delegate = self;
[audioPlay prepareToPlay];
[audioPlay play];
}
}
}
-(void)audioPlayerDidFinishPlaying:
(AVAudioPlayer *)player successfully:(BOOL)flag
{
if (player == audioPlay){
audioPlay = nil;
NSLog(@"audioplay = nil");
}
}
APCviewController.m,调用者作为一个按钮的动作:
- (IBAction)callPlay:(id)sender {
APCplayObject *a = [[APCplayObject alloc] init];
[a playAudio];
}
提前致谢。