【问题标题】:Playing back audio using AVAudioPlayer iOS 7使用 AVAudioPlayer iOS 7 播放音频
【发布时间】:2014-03-21 21:17:42
【问题描述】:

我很难按照 Apple 的文档来使用 AVAudioPlayer 类播放一个小的 .wav 文件。我也不确定基本音频播放需要哪些工具箱。到目前为止,我已经导入:

AVFoundation.framework
CoreAudio.framework
AudioToolbox.framework

这是我的代码.h.m

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

@interface ViewController : UIViewController <AVAudioPlayerDelegate>

- (IBAction)playAudio:(id)sender;

@end

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)playAudio:(id)sender {

    NSLog(@"Button was Pressed");

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"XF_Loop_028" ofType:@"wav"];
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];

    // create new audio player
    AVAudioPlayer *myPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
    [myPlayer play];

}
@end

我似乎没有任何错误。但是,我没有收到任何音频。

【问题讨论】:

    标签: ios core-audio


    【解决方案1】:

    您在这里遇到了 ARC 问题。 myPlayer 超出范围时正在清理。创建一个强大的属性,分配 AVAudioPlayer,你可能已经准备好了!

    @property(nonatomic, strong) AVAudioPlayer *myPlayer;
    
    ...
    
    // create new audio player
    self.myPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
    [self.myPlayer play];
    

    【讨论】:

    • 干杯 :-) 总而言之,我的 iOS 技能有点生疏,因为我刚刚在休息后重新开始学习它。
    【解决方案2】:

    filePath 是否返回一个有效值? fileURL 是否返回有效值?此外,您应该使用 AVAudioPlayer initWithContentsOfURL 的错误参数。如果您使用它,它可能会准确地告诉您问题所在。

    确保检查代码中的错误和无效值。检查 nil 文件路径和文件 URL 是第一步。接下来是检查错误参数。

    希望这会有所帮助。

    【讨论】:

    • 谢谢,我得看看 error 数据类型的文档。
    【解决方案3】:

    我所做的就是为此目的创建一个完整的微型课程。这样我就有了一个可以保留的对象,它本身也保留了音频播放器。

    - (void) play: (NSString*) path {
        NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];
        NSError* err = nil;
        AVAudioPlayer *newPlayer =
            [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: &err];
        // error-checking omitted
        self.player = newPlayer; // retain policy
        [self.player prepareToPlay];
        [self.player setDelegate: self];
        [self.player play];
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 2017-03-30
    相关资源
    最近更新 更多