我用谷歌搜索了这个问题,但找不到类似的案例。
我已经使用本教程播放 testSound.mp3 - 在 iPad 模拟器上点击按钮时的文件:http: //mobileorchard.com/easy-audio-playback-with-avaudioplayer/
如果 playSound-Method 在我的 ViewController.m 中,但不在我的 Sound.m 中(它具有相同的方法),它会以这种方式工作(它播放声音)。代码被执行(NSLog 说:“Sound.m playSound executed”),但根本没有声音。
我真的很感激这里的一些帮助,我想我完全被困住了...... :(
最好的问候, - 茶壶
// ViewController.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import "Sound.h"
@interface ViewController : UIViewController {
AVAudioPlayer *audioPlayer;
}
- (IBAction)pressButton:(id)sender;
- (void)playSound: (NSString*) soundFile volume : (NSInteger) volume repeats : (NSInteger) repeats;
@end
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading thea view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)pressButton:(id)sender {
NSLog (@"Method: pressButton");
[self playSound: @"testSound.mp3" volume: 2 repeats: 2 url : url]; //It works!
Sound *tempSound = [[Sound alloc] init];
[tempSound playSound: @"testSound.mp3" volume: 2 repeats: 2]; // Doesn't work. -> Says "Sound.m playSound executed", but there is no Sound.
}
- (void)playSound: (NSString*) soundFile volume : (NSInteger) volume repeats : (NSInteger) repeats {
NSLog(@"ViewControler playSound");
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
if (audioPlayer == nil){
NSLog([error description]);
NSLog(@"ViewController.m playSound NOT executed");
}
else{
[audioPlayer play];
NSLog(@"ViewController.m playSound executed");
}
}
@end
// 声音.h
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@interface Sound : NSObject {
AVAudioPlayer *audioPlayer;
}
- (void) playSound: (NSString*) soundFile volume : (NSInteger) volume repeats : (NSInteger) repeats;
@end
// 声音.m
#import "Sound.h"
@implementation Sound
- (void)playSound: (NSString*) soundFile volume : (NSInteger) volume repeats : (NSInteger) repeats {
NSLog(@"Sound playSound");
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
if (audioPlayer == nil){
NSLog([error description]);
NSLog(@"Sound.m playSound NOT executed");
}
else{
[audioPlayer play];
NSLog(@"Sound.m playSound executed");
}
}
@end