ios - AVAudioPlayer 不播放 mp3?

标签 ios xcode mp3 avaudioplayer

我想让我的 AVAudioPlayer 播放一些 mp3 文件。它可以播放其中的一些,但我有一个文件无法播放!

为了播放文件,我将它下载到我的设备上到应用程序文件夹中并以这种方式初始化它:

[[AVAudioPlayer alloc] initWithContentsOfURL:soundPath error:nil];

如何播放文件?为什么它不播放?

文件链接:abc.mp3

编辑:

(这里是显示错误的代码,代码里面有README,上机试试)

***.pch

#import <Availability.h>

#ifndef __IPHONE_4_0
#warning "This project uses features only available in iOS SDK 4.0 and later."
#endif

#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
    #import <SystemConfiguration/SystemConfiguration.h>
    #import <MobileCoreServices/MobileCoreServices.h>
    #import <AVFoundation/AVFoundation.h>
    #import <AudioToolbox/AudioToolbox.h>
#endif



ViewController.h

#import <UIKit/UIKit.h>
#import "AFNetworking.h"

@interface SCRViewController : UIViewController <AVAudioPlayerDelegate>
{
    UIButton *button;
    __block UIProgressView *view;
    NSOperationQueue *queue;
    __block BOOL isFile;
    UIButton *play;
    NSString *path;
    AVAudioPlayer *_player;
}

@end


ViewController.m

#import "ViewController.h"

@implementation SCRViewController

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

    button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundColor:[UIColor yellowColor]];
    [button setFrame:CGRectMake(50, 50, 220, 50)];
    [button addTarget:self action:@selector(download) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Download" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    [self.view addSubview:button];

    play = [UIButton buttonWithType:UIButtonTypeCustom];
    [play setBackgroundColor:[UIColor yellowColor]];
    [play setFrame:CGRectMake(50, 150, 220, 50)];
    [play addTarget:self action:@selector(play) forControlEvents:UIControlEventTouchUpInside];
    [play setTitle:@"Play" forState:UIControlStateNormal];
    [play setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [play setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    [self.view addSubview:play];

    self->view = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    self->view.frame = CGRectMake(10, 120, 300, 20);
    [self->view setProgress:0];
    [self.view addSubview:self->view];

    queue = [[NSOperationQueue alloc] init];

    isFile = NO;
}

- (void) download
{
    [button setBackgroundColor:[UIColor brownColor]];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
    [button setEnabled:NO];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://iwheelbuy.com/abc.mp3"]];

    //-------------------------------------------------------
    //-------------------------------------------------------
    // READ ME
    //-------------------------------------------------------
    //-------------------------------------------------------
    // Test in on device
    // I have uploaded another song for you. You can change link to http://iwheelbuy.com/def.mp3 and check the result
    // def.mp3 works fine on the device
    //-------------------------------------------------------
    //-------------------------------------------------------

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    path = [path stringByAppendingPathComponent:@"song"];

    if ( [[NSFileManager defaultManager] fileExistsAtPath:path])
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];

    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         isFile = YES;
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         //
     }];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
     {
         CGFloat done = (CGFloat)((int)totalBytesRead);
         CGFloat expected = (CGFloat)((int)totalBytesExpectedToRead);
         CGFloat progress = done / expected;
         self->view.progress = progress;
     }];
    [queue addOperation:operation];
}

- (void) play
{
    if (isFile)
    {
        NSError *error = nil;
        NSURL *url = [NSURL fileURLWithPath:path];
        _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
        if(error || !_player)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[error description] delegate:nil cancelButtonTitle:@"Try def.mp3" otherButtonTitles:nil];
            [alert show];
        }
        else
        {
            [_player play]; // plays fine
            [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
            [[AVAudioSession sharedInstance] setActive: YES error: nil];
        }
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Download the file plz" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alert show];
    }
}

@end

最佳答案

非 ARC

您必须在播放期间保留它,因为它不会保留自己。一旦被释放,它将立即停止播放。

圆弧

您需要在类中持有AVAudioPlayer 实例。并在它停止播放后释放它。例如,

#import <AVFoundation/AVFoundation.h>

@interface TAViewController () <AVAudioPlayerDelegate> {
    AVAudioPlayer *_somePlayer;   // strong reference
}
@end

@implementation TAViewController

- (IBAction)playAudio:(id)sender
{
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"kogmawjoke" withExtension:@"mp3"];
    _somePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
    _somePlayer.delegate = self;
    [_somePlayer play];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    if (player == _somePlayer) {
        _somePlayer = nil;
    }
}

@end

关于ios - AVAudioPlayer 不播放 mp3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12727672/

相关文章:

ios - 如何连接两个字段以使用 NSPredicate 进行搜索?

ios - Apple Watch 应用安装问题 - NSExtensionPointIdentifier

ios - 没有这样的模块 SDImageView

swift - Xcode 无法在类 UICollectionReusableView 的助理编辑器中打开正确的类

javascript - 获取歌曲的相对响度,Javascript

android - 如何从Android 4.0以上的Android设备(如Whatsapp)获取音频文件?

python - 带 Pyaudio 的 MP3

ios - 主线程在 viewDidLoad 中的并发队列上执行 dispatch_async,或者在方法内执行事务

ios - NSStream关闭和打开报错

iOS Metal 无法执行 'metal'(没有这样的文件或目录)