xcode 使用 AVFoundation 播放 wav 声音文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8323294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Playing wav sound file with AVFoundation
提问by Quaso
I am using AVFoundation to play wav files. But i could not make it play. Also no errors or warnings showed up.
我正在使用 AVFoundation 播放 wav 文件。但我无法让它播放。也没有出现错误或警告。
XCode is 4.2 and device is iOS 5.
XCode 是 4.2,设备是 iOS 5。
- (IBAction) playSelectedAlarm:(id)sender {
UIButton *button = (UIButton *)sender;
int bTag = button.tag;
NSString *fileName = [NSString stringWithFormat:@"%d23333", bTag];
NSLog(@"%@", fileName);
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];
AVAudioPlayer *theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:NULL];
theAudio.volume = 1.0;
theAudio.delegate = self;
[theAudio prepareToPlay];
[theAudio play];
}
回答by Quaso
Here is the solution;
这是解决方案;
I set AVAudioPlayer in header file..
我在头文件中设置了 AVAudioPlayer ..
@property (nonatomic, retain) AVAudioPlayer *theAudio;
@property (nonatomic, 保留) AVAudioPlayer *theAudio;
i guess 'retain' is solved my problem. Because after i sending "play", it sends "release" to balance the alloc. When AVAudioPlayer is deallocated it stops playing audio.
我想“保留”解决了我的问题。因为在我发送“播放”之后,它会发送“释放”来平衡分配。当 AVAudioPlayer 被释放时,它会停止播放音频。
回答by bndouglas
I have had the same issue with Xcode 4.5. Making the AVAudioPlayer into a strongly typed property made it play.
我在 Xcode 4.5 上遇到了同样的问题。使 AVAudioPlayer 成为强类型属性使其播放。
So the following code needs added to the @interface:
所以下面的代码需要添加到@interface:
@property (nonatomic, strong) AVAudioPlayer *theAudio;
The @implementation would then become:
然后@implementation 将变为:
- (IBAction) playSelectedAlarm:(id)sender {
UIButton *button = (UIButton *)sender;
int bTag = button.tag;
NSString *fileName = [NSString stringWithFormat:@"%d23333", bTag];
NSLog(@"%@", fileName);
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];
self.theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:NULL];
self.theAudio.volume = 1.0;
self.theAudio.delegate = self;
[self.theAudio prepareToPlay];
[self.theAudio play];
}