iphone - 没有声音在播放

标签 iphone ios4 memory audio

-(IBAction)test1
{
    CFBundleRef mainBundle = CFBundleGetMainBundle();

    CFURLRef soundFileURLRef;
    soundFileURLRef =CFBundleCopyResourceURL(mainBundle, 
                                             (CFStringRef) @"Bear3", CFSTR ("wav"), NULL);

    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef , &soundID);
    AudioServicesPlaySystemSound(soundID);
    AudioServicesDisposeSystemSoundID(soundID);
    CFRelease(soundFileURLRef);
}

它没有播放声音文件

最佳答案

您的代码无法正常工作,因为您在处理资源之前先将其处理掉。

AudioServicesDisposeSystemSoundID(soundID);

播放声音时不应调用。您需要重新组织代码。

如果更高级别的CF类可以完成此工作,则还应避免使用NS类。在这种情况下,他们可以。就是这样:

代码以回应评论:
SoundExampleViewController.h:
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
@interface SoundExampleViewController : UIViewController{
    SystemSoundID bear3SoundID;
}
-(IBAction)playSoundButtonPushed:(id)sender;
@end

SoundExampleViewController.m:
#import "SoundExampleViewController.h"
@implementation SoundExampleViewController
-(IBAction)playSoundButtonPushed:(id)sender{
    AudioServicesPlaySystemSound(bear3SoundID);
}
- (void)viewDidLoad{
    [super viewDidLoad];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Bear3" ofType:@"wav"]; 
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&bear3SoundID);
}
- (void)viewDidUnload{
    [super viewDidUnload];
    AudioServicesDisposeSystemSoundID(bear3SoundID);
}
@end

即使您坚持使用CF方法中的viewDidLoad类,也应遵循此常规布局。

关于iphone - 没有声音在播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8056246/

相关文章:

ios - arc4random 始终在应用程序启动时返回相同的初始值

c - 消息缓冲区的结构内存分配问题

c - 理解inotify示例中的对齐语句

ios - 阻止 UITableView 在 iOS 8 中自动滚动

iphone - UIImageView setImage 泄漏?

c++ - 使用 AVFoundation 为 iPhone 添加覆盖/操作?

memory - Rust 中的框类型在没有引用时会自动释放吗?

ios - 如何解决 iOS 9 自动布局问题?

iphone - View 的底部在模拟器和设备上被切断(单 View 应用程序)

ios - [UILabel copyWithZone :]: unrecognized selector