2009-12-29 33 views
13

cách dễ nhất để phát tệp nhạc như Mp3 với botton tạm dừng là gì? chơi rất đơn giản và nút khác tạm dừng nhạc đó .. bạn có thể viết mã đó không!Phát tệp MP3 bằng iPhone SDK

Trả lời

33

Đây là các mã dành cho các tác vụ được yêu cầu, appSoundPlayer là thuộc tính của AVAudioPlayer được khai báo trong tệp h. Ví dụ này cũng phát một bài hát trong thư mục tài nguyên.

#pragma mark - 
    #pragma mark *play* 
    - (IBAction) playaction { 

     NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"songname" ofType:@"mp3"]; 
     NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath]; 
     self.soundFileURL = newURL; 
     [newURL release]; 
     [[AVAudioSession sharedInstance] setDelegate: self]; 
     [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil]; 

    // Registers the audio route change listener callback function 
    AudioSessionAddPropertyListener (
            kAudioSessionProperty_AudioRouteChange, 
            audioRouteChangeListenerCallback, 
            self 
            ); 

    // Activates the audio session. 

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

    AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: nil]; 
    self.appSoundPlayer = newPlayer; 
    [newPlayer release]; 
    [appSoundPlayer prepareToPlay]; 
    [appSoundPlayer setVolume: 1.0]; 
    [appSoundPlayer setDelegate: self]; 
    [appSoundPlayer play]; 


    [stopbutton setEnabled:YES]; 
    [playbutton setEnabled: NO]; 
    playbutton.hidden=YES; 
    pausebutton.hidden =NO; 
}//playbutton touch up inside 

#pragma mark - 
#pragma mark *pause* 
-(IBAction)pauseaction { 
    [appSoundPlayer pause]; 
    pausebutton.hidden = YES; 
    resumebutton.hidden = NO; 

}//pausebutton touch up inside 

#pragma mark - 
#pragma mark *resume* 
-(IBAction)resumeaction{ 
    [appSoundPlayer prepareToPlay]; 
    [appSoundPlayer setVolume:1.0]; 
    [appSoundPlayer setDelegate: self]; 
    [appSoundPlayer play]; 
    playbutton.hidden=YES; 
    resumebutton.hidden =YES; 
    pausebutton.hidden = NO; 

}//resumebutton touch up inside 

#pragma mark - 
#pragma mark *stop* 
-(IBAction)stopaction{ 

    [appSoundPlayer stop]; 
    [playbutton setEnabled:YES]; 
    [stopbutton setEnabled:NO]; 
    playbutton.hidden=NO; 
    resumebutton.hidden =YES; 
    pausebutton.hidden = YES; 

}//stopbutton touch up inside 
+0

bạn có mã mẫu của hướng dẫn này không? – Momi

+1

những lỗi đó là do bạn chưa khai báo chúng trong tệp h. – Nithin

+0

Mã này có hoạt động cho NSURL ... phát âm thanh đệm từ máy chủ không? –

7

cũng here là một hướng dẫn có sẵn.

Chủ đề là

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]]; 

    NSError *error; 
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
    audioPlayer.numberOfLoops = -1; 

[audioPlayer play]; 

và khi bạn muốn tạm dừng;

[audioPlayer pause]; 

hy vọng điều này sẽ hữu ích.

+1

cảm ơn tôi rất nhiều http://stackoverflow.com và tất nhiên bạn: D – Momi

+0

OK, tôi có một số vấn đề một lần nữa. khi tôi nhấn vào nút phát nhiều lần, nhạc sẽ phát và bật ... !! làm thế nào có thể chơi nhạc 1 lần? và về nút tạm dừng, ai làm việc đó? xin lỗi iam nghiệp dư: – Momi

25

Đối với âm thanh ngắn hoặc khi nghe nhạc MP3 không chơi tốt trên các mã đề nghị bạn luôn có thể sử dụng:

SystemSoundID soundID; 
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/sound.mp3", [[NSBundle mainBundle] resourcePath]]]; 

AudioServicesCreateSystemSoundID((CFURLRef)url, &soundID); 
AudioServicesPlaySystemSound (soundID); 

Đừng quên thêm:

#import <AudioToolbox/AudioToolbox.h> 
+0

cảm ơn rất nhiều vì điều này! – rwarner

+1

Cảm ơn, đã làm việc cho tôi. Với ARC: AudioServicesCreateSystemSoundID ((__ bridge CFURLRef) url & soundID); –

0

Các oalTouch mẫu mã trên trang web dành cho nhà phát triển Apple iOS thực hiện những gì bạn muốn và sẵn sàng chạy. Nó cũng cho thấy làm thế nào để kiểm tra nếu một ứng dụng khác (ví dụ như ipod) đang chơi một tập tin đã có, đó là tiện dụng nếu bạn muốn cho phép người dùng của bạn để nghe nhạc riêng của họ thay vì của bạn.

5

Tôi sợ câu trả lời nói không còn hoạt động trong iOS 7 trở lên. Bạn sẽ cần phải sử dụng đoạn mã sau:

trong file header (.h)

Để xử lý các phương pháp đại biểu như khi chơi các âm thanh đã hoàn tất audioPlayerDidFinishPlaying :, kế thừa từ AVAudioPlayerDelegate.

@property (nonatomic, strong) AVAudioPlayer *player; 

trong file thi hành (.m)

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: resourceName 
                  ofType: @"mp3"]; 
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath]; 

AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL 
                    error: nil]; 
_player = newPlayer; 
[_player prepareToPlay]; 
[_player setDelegate: self]; 
[_player play]; 
1

Tôi thích mã đơn giản và đây là giải pháp của tôi: (. Hãy nhớ thêm nút chuyển đổi để có được chơi nhạc Have fun)

#import "ViewController.h" 
#import <AVFoundation/AVFoundation.h> 

@interface ViewController() 
{ 
    NSURL*     bgURL; 
    AVAudioPlayer*   bgPlayer; 
} 
@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    bgURL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"mp3"]]; 
    bgPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:bgURL error:nil]; 
} 

#pragma mark AVAudioPlayer 
- (IBAction)toggleMusic:(UISwitch*)sender { 
    NSLog(@"togging music %s", sender.on ? "on" : "off"); 

    if (bgPlayer) { 

     if (sender.on) { 
      [bgPlayer play]; 
     } 
     else { 
      [bgPlayer stop]; 
     } 
    } 
}