[英]Playing back audio using AVAudioPlayer iOS 7
我正在努力遵循Apple的有关使用AVAudioPlayer
类播放小的.wav
文件的文档。 我也不确定基本音频播放需要哪些工具箱。 到目前为止,我已经导入:
AVFoundation.framework
CoreAudio.framework
AudioToolbox.framework
这是我的代码.h
和.m
:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController : UIViewController <AVAudioPlayerDelegate>
- (IBAction)playAudio:(id)sender;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)playAudio:(id)sender {
NSLog(@"Button was Pressed");
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"XF_Loop_028" ofType:@"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
// create new audio player
AVAudioPlayer *myPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
[myPlayer play];
}
@end
我似乎没有任何错误。 但是,我没有任何音频。
filePath是否返回有效值? fileURL是否返回有效值? 另外,您应该使用AVAudioPlayer initWithContentsOfURL的error参数。 如果使用它,它可能会完全告诉您问题所在。
确保检查代码中的错误和无效值。 第一步是检查nil文件路径和fileURL。 接下来检查错误参数。
希望这可以帮助。
您在这里遇到ARC问题。 超出范围时,将清理myPlayer。 创建一个强大的属性,分配AVAudioPlayer,您可能已经准备就绪!
@property(nonatomic, strong) AVAudioPlayer *myPlayer;
...
// create new audio player
self.myPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
[self.myPlayer play];
我要做的就是为此目的创建一个整个微型类。 这样,我就有了一个可以保留的对象,它本身也保留了音频播放器。
- (void) play: (NSString*) path {
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];
NSError* err = nil;
AVAudioPlayer *newPlayer =
[[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: &err];
// error-checking omitted
self.player = newPlayer; // retain policy
[self.player prepareToPlay];
[self.player setDelegate: self];
[self.player play];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.