使用AVAudioPlayer播放声音时出现问题

时间:2018-09-19 12:48:06

标签: ios objective-c

我想播放wav / mp3格式的声音。我正在使用AVAudioPlayer。问题是在听筒中听得见,但是当我取下听筒时,没有声音。我已经搜索并尝试了此处给出的一些建议,但结果是相同的。请帮我解决这个问题。谢谢

- (void)viewDidLoad
{
    [super viewDidLoad];
       NSString *path = [NSString stringWithFormat:@"%@/Right Side Stress Increasing.mp3", [[NSBundle mainBundle] resourcePath]];
        NSURL *soundUrl = [NSURL fileURLWithPath:path];

        // Create audio player object and initialize with URL to sound
        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
}

- (IBAction)playButtonTapped:(id)sender
{
    //play sound
     [_audioPlayer play];
}

2 个答案:

答案 0 :(得分:1)

AVAudioPlayer如果设备处于静音模式,则不会播放声音。

您可以启用使用AVAudioSession

目标-C

#import <AVFoundation/AVFoundation.h>

NSError *error = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error: nil];
[[AVAudioSession sharedInstance] setActive:YES error:&error];

SWIFT

import AVFoundation

do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    try AVAudioSession.sharedInstance().setActive(true)
}
catch {
    print(error)
}

答案 1 :(得分:0)

将音量设置为最大。 1.0是最大音量水平0.0是最小音量水平

  - (void)viewDidLoad
    {
        [super viewDidLoad];
           NSString *path = [NSString stringWithFormat:@"%@/Right Side Stress Increasing.mp3", [[NSBundle mainBundle] resourcePath]];
            NSURL *soundUrl = [NSURL fileURLWithPath:path];

            // Create audio player object and initialize with URL to sound
            _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
            _audioPlayer.volume = 1.0
    }

    - (IBAction)playButtonTapped:(id)sender
    {
        //play sound
         [_audioPlayer play];
    }