【问题标题】:Unable to play sound (wav) on event无法在事件中播放声音 (wav)
【发布时间】:2011-09-30 15:28:10
【问题描述】:

我需要播放短音。这是我写的代码

在我的标题中我有:

#import <AVFoundation/AVFoundation.h>

@interface AddItemController : UIViewController < ... , AVAudioPlayerDelegate> {
...
AVAudioPlayer *audio;
}

...
@property (nonatomic, retain) IBOutlet AVAudioPlayer *audio;

@end

.m 文件中:

- (void)playSound {
    NSURL *url;
    if (error) {
        url =[NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Resources/error.wav"]];
    } else {
        url =[NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Resources/finished.wav"]];
    }
    audio = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    audio.delegate = self;
    [audio play];
}

-(IBAction)addItem:(id)sender { 
    if ( ... ) {
        error = true;
        [self playSound];
        return;
    }

    ...

    error = false;
    [self playSound];
}

代码没有警告也没有问题。所有其他功能都在工作。只是我听不到任何声音。

#

好的!我自己找到了解决方案。打扰了,对不起。

希望我的解决方案对某人有用。

- (void)playSound
{
    NSURL *url;

    NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"error.aif"];

    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        url = [NSURL fileURLWithPath:path];
        audio = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        [audio prepareToPlay];
    }
    [audio play];
}

【问题讨论】:

    标签: iphone objective-c ios audio avfoundation


    【解决方案1】:

    您可能需要查看AudioToolbox 框架中的AudioServicesCreateSystemSoundIDAudioServicesPlaySystemSound 函数。

    【讨论】:

    • AVSudioPlayer 不打算以任何方式呈现播放器,您正在考虑 AVPlayer。
    • 哎呀,我的错...更正了答案,谢谢... :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    相关资源
    最近更新 更多