xcode Objective-C 无法使用 AVAudioPlayer 播放声音
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32707185/
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
Objective-C can't play sound with AVAudioPlayer
提问by user979331
I am using XCode 7 with iOS 9 and I am trying to play a sound. I have been googling for a solution for days and I have tried every possible solution out there and nothing is working.
我在 iOS 9 上使用 XCode 7,我正在尝试播放声音。我一直在谷歌上搜索解决方案好几天了,我已经尝试了所有可能的解决方案,但没有任何效果。
Here is my code
这是我的代码
.h
。H
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController : UIViewController <DTDeviceDelegate, AVAudioPlayerDelegate>
{
}
and here is my .m file:
这是我的 .m 文件:
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"autumn_leaves" ofType:@"m4a"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSError *error;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL
error:&error];
player.numberOfLoops = -1; //Infinite
[player play];
and no sound, no errors, no warnings nothing at all
没有声音,没有错误,没有警告,什么都没有
soundFilePath
and soundFileURL
are not nil
, same with player, they are getting populated. My phone volume is as loud as it can be.
soundFilePath
并且soundFileURL
不是nil
,与玩家一样,他们越来越多。我的电话音量尽可能大。
I have also tried in .m file:
我也在 .m 文件中尝试过:
@property(strong, nonatomic) AVAudioPlayer *player;
self.myPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:&error];
[self.myPlayer play];
Also did not play sound and no errors.
也没有播放声音,也没有错误。
Here is a screenshot of my Resources folder:
这是我的资源文件夹的屏幕截图:
Please Help!
请帮忙!
回答by Bassl Kokash
Define AVAudioPlayer as a property, and it should work. You could implement the AVAudioPlayerDelegate if you want, its not a must.
将 AVAudioPlayer 定义为一个属性,它应该可以工作。如果需要,您可以实现 AVAudioPlayerDelegate,这不是必须的。
For detailed explanation check this answer https://stackoverflow.com/a/8415802/1789203
有关详细说明,请查看此答案https://stackoverflow.com/a/8415802/1789203
@interface ViewController ()
@property (nonatomic,strong)AVAudioPlayer *player;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"bush_god_bless" ofType:@"wav"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSError *error;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL
error:&error];
self.player.numberOfLoops = 0; //Infinite
self.player.delegate = self;
[self.player play];
}
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
NSLog(@"%d",flag);
}
回答by Idali
You need to set delegate to self before [player play];
[player play]前需要设置delegate为self;
player.delegate = self;
[player play];