【问题标题】:AVAudioPlayer does not give error but not playing soundAVAudioPlayer 不报错但不播放声音
【发布时间】:2016-07-06 18:35:50
【问题描述】:

你好,我是苹果开发的新手

我在 iPhone 上运行代码没有错误,但我听不到声音 这是代码

-(void) buttonPressed1:(UIButton *)sender{  
    NSString *fileName = @"Record_000";
    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 prepareToPlay];
    [self.theAudio play];
}

这是我的 h 文件

#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>
@interface StartPage : UIViewController
@property (nonatomic, strong) AVAudioPlayer *theAudio;
@end

【问题讨论】:

  • 添加一个 NSError *error 并替换 self.theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];这样你就可以用 NSLog("error = %@",error);
  • 但我没有收到错误,我按下按钮并没有声音
  • @user3218241- 是否已将按钮操作与按钮连接
  • 仅当我将音频文件的名称更改为不存在的 1 时才会出错
  • 您是否尝试过其他音频文件?

标签: ios objective-c xcode avaudioplayer


【解决方案1】:

尝试设置音频会话:

#import <AVFoundation/AVAudioSession.h>

    -(void) viewDidLoad
    {
        [super viewDidLoad];
        [self setAudioSession];
    }

    -(void) setAudioSession
    {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        NSError *sessionError = nil;
        BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
        if (!success)
        {
            NSLog(@"Setting Audio Session Category Error: %@", sessionError);
        }
        success = [audioSession setActive:YES error:&sessionError];
        if (!success)
        {
            NSLog(@"Setting Audio Session Active Error: %@", sessionError);
        }
    }

【讨论】:

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