【问题标题】:Objective-C can't play sound with AVAudioPlayerObjective-C 不能用 AVAudioPlayer 播放声音
【发布时间】:2015-12-18 20:37:31
【问题描述】:

我在 iOS 9 中使用 XCode 7,我正在尝试播放声音。几天来我一直在谷歌上寻找解决方案,我已经尝试了所有可能的解决方案,但没有任何效果。

这是我的代码

.h

#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController <DTDeviceDelegate, AVAudioPlayerDelegate>
{

}

这是我的 .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];

没有声音,没有错误,没有警告,什么都没有

soundFilePathsoundFileURL 不是 nil,与播放器一样,它们正在被填充。我的手机音量尽可能大。

我也尝试过 .m 文件:

@property(strong, nonatomic) AVAudioPlayer *player;

self.myPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:&error];
[self.myPlayer play];

也没有播放声音也没有报错。

这是我的资源文件夹的屏幕截图:

请帮忙!

【问题讨论】:

  • 尝试使用 .caf 文件而不是任何其他类型。它对我有用。

标签: ios objective-c xcode audio avaudioplayer


【解决方案1】:

你需要在[player play]之前将delegate设置为self;

player.delegate  = self;
[player play];

【讨论】:

    【解决方案2】:

    将 AVAudioPlayer 定义为属性,它应该可以工作。 如果需要,您可以实现 AVAudioPlayerDelegate,这不是必须的。

    有关详细说明,请查看此答案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);
    }
    

    【讨论】:

    猜你喜欢
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 2011-12-22
    相关资源
    最近更新 更多